DockerNetworking

Nginx as a Reverse Proxy in Docker

One nginx at the edge of the server, proxy_pass to service names, the X-Forwarded headers, and simple paths to HTTPS.

Nginx as a Reverse Proxy in Docker
Table of contents
  1. Structure
  2. The nginx.conf file
  3. TLS: a free Let's Encrypt certificate
  4. Keep the site URL in line

When several services run on one server, only one of them can own port 80. The standard solution is a single nginx at the edge of the server that forwards requests to the containers behind it based on the domain name.

Structure

nginx is itself a Compose service, and every other service runs on the internal network without publishing ports (no ports: section):

services:
  nginx:
    image: nginx:stable-alpine
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
    networks: [wp-net]

  wordpress:
    image: wordpress:latest
    # no ports: reachable only from inside wp-net
    networks: [wp-net]

The nginx.conf file

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://wordpress:80;
        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;
    }
}

Two things to notice: proxy_pass points at the service name (wordpress), not an IP, because Compose’s DNS resolves it. And passing the X-Forwarded-* headers lets WordPress see the visitor’s real IP and scheme; without them, every visit is logged as coming from the nginx container’s IP.

TLS: a free Let’s Encrypt certificate

A simple way to start is an nginx container plus a companion container that obtains and renews certificates automatically. If nginx runs on the host instead, Certbot handles everything; see free SSL with Let’s Encrypt for Nginx. For people who would rather not maintain nginx configuration at all, Caddy is the low-effort option: a web server that reduces HTTPS setup to a single example.com line and obtains and renews certificates by itself.

Keep the site URL in line

Once the site sits behind a proxy and moves to HTTPS, update the site URL (for example WP_URL in your .env) to the real address, such as https://example.com, so WordPress, the sitemap and internal links are all generated with the correct domain.

About the author

Arash Karimian

Network and infrastructure engineer with years of day-to-day work on Linux servers, firewalls and network tuning. Writes about networking, security and server troubleshooting.

All articles by Arash Karimian

Comments

No comments yet. For technical questions, include the details (OS version, the exact error and the command you ran) to get a precise answer.

Leave a comment