Nginx Load-Balancing – 502 Bad Gateway on Reverse-Proxy Multiports

load balancingnginxreverse-proxyssl

I used two Icecast servers which host many webradios streams.
Each stream use a port between 8000 and 9000.

I use nginx (1.16.1 on Debian 10) to :

  • easily allow HTTPS for all streams
  • automatically change server on failure (ex.: server down). (high-availability / load-balance)

In fact, this is what I wish :

When user listen a stream on https://hosting.mydomain.com:8xxx ,
I want to transparently (proxify) send the request on one of the two Icecast's server.

Example :

If HTTPS and Icecast_1 is alive then send the request to Icecast_1.

If HTTPS and Icecast_1 is down then send the request to Icecast_2.

To do it, I've set the following :

#Icecast's cluster :
upstream backend {
    ip_hash;
    keepalive 64;
    #Icecast 1 :
    server 10.1.0.101 ;
    #Icecast 2 :
    server 10.1.0.102 ;

}


#SSL for all
server {

        listen 8000-9000 ssl ;
        server_name hosting.mydomain.com;

        access_log /var/log/nginx/reverse-ssl-access.log;
        error_log /var/log/nginx/reverse-ssl-error.log;

        # ssl on;
        ssl_protocols TLSv1.2 TLSv1.1 TLSv1 ;
        ssl_certificate /etc/letsencrypt/live/hosting.mydomain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/hosting.mydomain.com/privkey.pem;

        location / {
               resolver 8.8.8.8;
               proxy_pass http://backend:$server_port;
        }

}

I've a problem when I try to do something like this : "http://backend:$server_port".

In the web browser I've the error : 502 Bad gateway

In the errors logs on the server : *1 no resolver defined to resolve backend .

Can you help me ?

Best Answer

You need to set the server port in the upstream configuration. Check if you can use the $server_port in stead of 6789.

upstream backend {
 ip_hash;
 keepalive 64;
 #Icecast 1 :
 server 10.1.0.101:6789 ;
 #Icecast 2 :
 server 10.1.0.102:6789 ;
}

server {

    listen 8000-9000 ssl ;
    server_name nginx.mydomain.com;

    access_log /var/log/nginx/reverse-ssl-access.log;
    error_log /var/log/nginx/reverse-ssl-error.log;

    # ssl on;
    ssl_protocols TLSv1.2 TLSv1.1 TLSv1 ;
    ssl_certificate /etc/letsencrypt/live/hosting.mydomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/hosting.mydomain.com/privkey.pem;

    location / {
           proxy_pass http://backend;
    }

}

If you want to use $server_port, you can't use upstream, so, no load balancing.

    location / {
        proxy_pass http://10.1.0.101:$server_port;
    }