caleale90
caleale90

Reputation: 170

Reverse Proxy with NGINX and Docker

I have an application running on http://localhost:8000 using a docker image that was made by me.

Now I want to use NGINX as reverse proxy listening on port 80, to redirect to the localhost:8000.

Here my nginx.conf file

#user  nobody;
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    server {
        listen 80;
        location / {
            proxy_pass http://localhost:8000;
        }
    }
}

Here my Dockerfile:

FROM nginx

RUN rm /etc/nginx/conf.d/default.conf

COPY index.html /usr/share/nginx/html
COPY nginx.conf /etc/nginx

CMD nginx

To build the image I use the command

docker build --no-cache -t mynginx .

To run it, I use

docker run -p 80:80 -d mynginx 

Now, if I test from my local computer with curl localhost:8000 everything works, but if I try with curl localhost, I get a Bad Gateway error.

Moreover, I tried to serve static content and it works, but with the reverse proxy settings it does not work.

Upvotes: 4

Views: 2043

Answers (2)

matt
matt

Reputation: 4047

The reason you are getting a bad gateway is that from within your nginx container, localhost resolves to the container itself and not to the host system.

If you want to access your application container from your reverse proxy container, you need to put both containers into a network.

docker network create my-network
docker network connect --alias application my-network <application container id/name>
docker network connect --alias reverse-proxy my-network <reverse proxy container id/name>

--network can be an arbitrary name and --alias should be the hostnames you want to resolve to your containers. In fact you do not need to provide an alias if you already assigned a (host)name (docker run --name ...) to your containers.

You can then change your proxy_pass directive to the (alias) name of your application container:

proxy_pass http://application:8000;

Also refer to the documentation: Container networking

Upvotes: 1

Siyu
Siyu

Reputation: 12129

curl localhost:8000 works => your application is running

curl localhost returns bad gateway means proxy_pass http://localhost:8000; does not work. This is because "localhost" is relative to its caller, in this case the nginx container, which does not have anything running on port 8000.

You need to point it to your application using proxy_pass http://your_app:8000; where "your_app" is the service name (docker-compose) or the container name or its network alias. Make sure they are in the same network.

Upvotes: 0

Related Questions