Dorokhov.codes

04. Setting up a reverse proxy

A reverse proxy server is a server that typically sits in front of other web servers in order to provide additional functionality.

The issue

Docker containers are assigned random IPs and ports which makes addressing them much more complicated from a client perspective. By default, the IPs and ports are private to the host and cannot be accessed externally unless they are bound to the host.

Binding the container to the hosts port can prevent multiple containers from running on the same host. For example, only one container can bind to port 80 at a time. This also complicates rolling out new versions of the container without downtime since the old container must be stopped before the new one is started.

A reverse proxy can help with these issues as well as improve availability by facilitating zero-downtime deployments.

Installation nginx-proxy

There’s a nice solution: nginx-proxy.

To start the reverse proxy:

docker container run -d \
      -p 80:80 \
      -v /var/run/docker.sock:/tmp/docker.sock:ro \
      nginxproxy/nginx-proxy

Or using docker-compose.yml:

version: '2'

services:
  reverse-proxy:
    container_name: reverse-proxy
    image: nginxproxy/nginx-proxy
    ports:
      - "80:80"
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro

networks:
  default:
    name: reverse-proxy

Attaching new containers

To make our containers work with the reverse proxy, we need to do two things:

  • Expose a port.
  • Set a VIRTUAL_HOST variable.

Example of some container configuration:

version: '2'

services:
  app:
    container_name: dorokhov.codes
    image: dorokhov.codes
    expose:
      - "80"
    environment:
      VIRTUAL_HOST: dorokhov.codes

networks:
  default:
    name: dorokhov.codes

And we have to add our reverse proxy container to the dorokhov.codes network:

docker network connect dorokhov.codes reverse-proxy