Nginx: 502 Bad Gateway within docker stack

Viewed 8348

I have docker stack running 2 containers, first is Nginx, second - application.

The problem is that nginx shows Bad Gateway error:

Here is nginx conf:

upstream example {
  server mystack_app1;  
  # Also tried with just 'app1'
  # server mystack_app2;

  keepalive 32;
}

server {
    listen 80;
    server_name example;

    location / {
                proxy_pass http://example;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_connect_timeout 150;
                proxy_send_timeout 100;
                proxy_read_timeout 100;
                proxy_buffers 4 32k;
                client_max_body_size 8m;
                client_body_buffer_size 128k;
        }
}

Here is docker-compose.yml

version: "3"
services: 

  app1:
    image: my-app:latest    
    ports:
      - "9000:9000"
    networks:
      - webnet  

  web:
    image: my-web:latest    
    ports:
      - "81:80"
    networks:
      - webnet
    deploy:      
      restart_policy:
        condition: on-failure        

networks:
  webnet:

I use following command to deploy docker stack:

docker stack deploy -c docker-compose.yml mystack

So I can access application from host's browser by localhost:9000 - it works ok.

Also, from the nginx container, I can ping mystack_app1.

But when accessing localhost:81, nginx shows 502 Bad Gateway

Please help.

1 Answers

It looks like your upstream definition is not correct. It's trying to connect to port 80 instead of port 9000.

Try

upstream example {
  server mystack_app1:9000;  
  # Also tried with just 'app1'
  # server mystack_app2;

  keepalive 32;
}

Btw, I suggest you to use the container_name in your docker-compose file.

Related