How to setup Nginx reverse proxy in Docker on Ubuntu 22.04

If you have multiple services running internally, and don’t have public IP’s (or don’t want) to expose these services, a reverse proxy can come in handy. A reverse proxy can also be useful when one wants to forward connections to other URLs.

docker-compose.yaml

version: "3.3"

services:

   web:
     image: nginx
     volumes:
       - ./config/nginx.conf:/etc/nginx/nginx.conf:ro
     ports:
       - "8080:80"
       - "docker-service-port-1:external-port-1"
       - "docker-service-port-2:external-port-2"
     environment:
       - NGINX_HOST=service.yourdomain.com
       - NGINX_PORT=80

config/nginx.conf

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


stream {
    server {
        listen     external-port-1;
        proxy_pass address_to_forward_connection_to;
    }

    server {
        listen     external-port-2;
        proxy_pass address_to_forward_connection_to;
    }
}