Iñigo
Iñigo

Reputation: 2016

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

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:

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?

Upvotes: 1

Views: 748

Answers (1)

matic1123
matic1123

Reputation: 1119

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.

Upvotes: 3

Related Questions