TonyW
TonyW

Reputation: 18895

Setting nginx reverse proxy to serve from another docker container

I have an app in a docker container running at the port number 3000, exposed to the host (port 3050 mapped to the container's port 3000), and I would like to use this nginx-proxy to point urls like http://localhost/users to point/proxy to http://localhost:3050/users.

I have this block in my docker-compose.yml file:

 nginx_service:
   image: jwilder/nginx-proxy
   container_name: nginx_server
   ports:
    - "80:80"
    - "443:443"
   volumes:
    - ./ssl_certs:/etc/nginx/certs
    - /var/run/docker.sock:/tmp/docker.sock:ro

Below is the container defined in docker-compose.yml that runs my app on the port 3000 in the docker container:

api:
   build: .
   container_name: api
   environment:
    - VIRTUAL_HOST= service.myserver.com
    - VIRTUAL_PROTO=https
   volumes:
    - "./API:/host"
   links:
    - Mongo:Mongo
   ports:
    - "3050:3000"

After I start up the docker containers, I can open http://localhost:3050/users in browser, but not http://localhost/users, which gives me a 503 error for Service Temporarily Unavailable.

Maybe I am getting the whole idea wrong, could someone help or correct me with nginx reverse proxy?

Upvotes: 3

Views: 6342

Answers (1)

TonyW
TonyW

Reputation: 18895

After doing some search, I was able to pull together a working docker-compose.yml that has a working nginx reverse proxy (image: jwilder/nginx-proxy in docker hub) to the node.js-based web app I have in a separate container.

The key to making it work is following:

  1. set the VIRTUAL_HOST=port in the nginx reverse proxy container, this port should be the port that my node.js app runs in its container (not the port mapped on the host!)
  2. If you want the nginx reverse proxy to be on https, you should set up an SSL certificate, but should set http (not https) to the environment variable VIRTUAL_PROTO=http in the web app container.

Below is the working docker-compose.yml:

nginx_service:
   image: jwilder/nginx-proxy
   container_name: nginx_server
   ports:
    - "80:80"
    - "443:443"
   volumes:
    - ./ssl_certs:/etc/nginx/certs
    - /var/run/docker.sock:/tmp/docker.sock:ro
   environment:
    - VIRTUAL_PORT=3000  # 3050 port on host does not work!


api:
   build: .
   container_name: api
   environment:
    - VIRTUAL_HOST=service.myserver.com
    - VIRTUAL_PROTO=http   # should be http even if you use https to the proxy, because node.js uses http!
   volumes:
    - "./API:/host"
   links:
    - Mongo:Mongo
   ports:
    - "3050:3000"

Hope this will help someone landing on this page from a search engine some day!

Upvotes: 8

Related Questions