Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx docker container proxy pass to another port

Tags:

docker

nginx

I want to run Nginx in a docker container, it listens to port 80 and I want it to proxy_pass to port 8080 when the url starts with word api, and I have some web app listening port 8080. This has been working for me without docker, but with docker, I couldn't get it to work.

My nginx.conf is like:

    location /{
        # serve static page
    }
    location /api {
        proxy_pass http://0.0.0.0:8080;
    }

I run my nginx container with docker run -d -p 80:80 -p 8080: 8080 nginx

My problem is now I can no longer run my web app because it can't listen to port 8080 since that container is already listening to it.

like image 518
Arch1tect Avatar asked Jan 27 '26 04:01

Arch1tect


2 Answers

docker run -d --net host nginx

Try it! Nginx container will share the host network with IP and all ports

like image 134
亚里士朱德 Avatar answered Jan 29 '26 03:01

亚里士朱德


First, you need to create a network to place both containers:

docker network create nginx_network

Then, you should specify Docker's DNS server in nginx configuration:

location /api {
    #Docker DNS
    resolver 127.0.0.11;

    #my_api - name of container with your API, see below
    proxy_pass http://my_api:8080;
}

Finally, run your containers:

docker run --network="nginx_network" -d --name my_api your_api_container
docker run --network="nginx_network" -d -p 80:80 nginx

Note:

  1. --name parameter's value for API's container must match domain name in Nginx config
  2. it's enough to specify only 80 port for your nginx container
  3. first run your API's container and then Nginx's container (see below)
  4. both containers must be in the same network

This should work.

In case if you run nginx container first, then nginx will try to resolve domain name my_api on startup and fail, because container with this name doesn't exist yet. In this case there is a following workaround (not sure if it is good solution). Modify nginx config:

location /api {
    #Docker DNS
    resolver 127.0.0.11;

    #hack to prevent nginx to resolve domain on start up
    set $docker_host "my_api";

    #my_api - name of container with your API, see below
    proxy_pass http://$docker_host:8080;
}
like image 23
Marat Safin Avatar answered Jan 29 '26 04:01

Marat Safin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!