Search code examples
dockernginx

nginx docker cannot pass proxy to localhost keeps giving 502 bad gateway


I am trying to set up a proxy docker and forward it to a server running outside the docker on localhost.

my yml file

services:
    proxy:
        image: nginx:alpine
        volumes:
          - "./nginx.conf:/etc/nginx/nginx.conf"
        ports:
          - "0.0.0.0:9020:9020"
        environment:
          - TZ=Europe/Amsterdam
        healthcheck:
          interval: 15s
          test: ["CMD-SHELL", "curl --fail -s http://localhost:9020/health || exit 1"]
        extra_hosts:
          - "host.docker.internal:host-gateway"

my nginx.conf:

# Nginx expects this section to be defined, even if empty
events {

}

http {
    server {
       server_name "proxy";
        location / {
            proxy_pass http://host.docker.internal;
        }
        location /health {
            access_log off;
            add_header 'Content-Type' 'text/plain';
            return 200 "healthy\n";
        }
        listen 9020;
    }
}

exits with error:

2024/03/14 12:03:53 [error] 22#22: *1 connect() failed (110: Operation timed out) while connecting to upstream, client: 192.168.32.1, server: proxy, request: "GET / HTTP/1.1", upstream: "http://172.17.0.1:80/", host: "localhost:9020"

I tried proxy_pass http://172.17.0.1;


Solution

  • If you access a service outside the docker network make sure to open that port on the host machine:

    sudo ufw allow 9000