How to forward Nginx incoming request to Docker container port

Table of Content

Some time ago we decided fully migrate projects on one our server to Docker. There was no problem write Dockerfile according to each project, but we don’t know how to make Docker container accessible by domain.

Supposed, we have next configuration in docker-compose.yml:

version: '3.7'

services:
  ...
  webserver:
    image: nginx:1.16
    restart: unless-stopped
    ports:
      - "8080:80"
    volumes:
      - .:/var/www/html
   ...

In the example above, we just make port forwarding from 80 port of Docker container to 8080 port of our real server.

Take a note to restart: unless-stopped, this automatically start Docker container even after a server reboot.

The solution was straightforward simply, you should use proxy_pass in your Nginx server block configuration to forward all incoming requests to Docker port.

server {
    listen 80;

    server_name example.com;

    location / {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;

        proxy_pass http://localhost:8080/;
    }
}

Check Nginx configuration and restart web-server

nginx -t
systemctl restart nginx

There is no (almost) limit in using ports, so you can use any port such as 8081, 8082 etc.

Leave a Reply

Your email address will not be published. Required fields are marked *