Home > Mobile >  Docker - Nginx proxy_pass "502 bad gateway" only with client routes?
Docker - Nginx proxy_pass "502 bad gateway" only with client routes?

Time:06-09

I have the following docker compose:

version: '3.1'

services:

  backend:
    container_name: backend
    image: backendnode
    restart: always
    ports:
      - 3000:3000

  frontend:
    container_name: frontend
    image: frontnginx
    restart: always
    ports:
      - 4200:80

  apigw:
    image: reverseproxy
    restart: always
    ports:
      - 80:80
    depends_on: 
      - frontend
      - backend

This is the reverseproxy image nginx.conf:

worker_processes auto;
  
events { worker_connections 1024; }

http {

    server {
        listen 80;
        server_name localhost 127.0.0.1;
 
        location / {
            proxy_pass         http://frontend:4200;
            proxy_set_header   X-Forwarded-For $remote_addr;
        }
        location /api {
            proxy_pass         http://backend:3000;
            proxy_set_header   X-Forwarded-For $remote_addr;
        }
    }
 
}

When running docker-compose run, I get the following results:

  • localhost:80/api/users: works great, nginx redirects to backend properly.
  • localhost:80/index.html: not working, I get the following error:

connect() failed (111: Connection refused) while connecting to upstream, client: 172.20.0.1, server: localhost, request: "GET /index.html HTTP/1.1", upstream: "http://172.20.0.5:4200/index.html", host: "localhost:80"

Frontend is a simple nginx web server, this is its nginx.conf:

events{}

http {

    include /etc/nginx/mime.types;

    server {
        listen 80;
        server_name localhost;
        root /usr/share/nginx/html;
        index index.html;

        location / {
            try_files $uri $uri/ /index.html;
        }
    }
}

Any idea why reverse proxy it's not working with frontend routes?

CodePudding user response:

Created answer from the comment thread: Docker networking works like this: if you use communication within docker's network, you need to refer to the internal ports. Since port mapping is used for the "outside world". So in your case, you would need to refer to "frontend:80" instead of 4200.

  • Related