The blog about containerisation, virtual machines and useful shell snippets and findings

Proper jwilder/nginx-proxy usage by example.

Imagine, you have several containers and nginx-proxy in front. And server runs under CoreOS. What’s the proper configuration for startup?

Here is schema I use in production CoreOS. We need to create separate network for all frontend containers, in my case network name is ‘nginx-proxy’.

  1. Create following nginx-proxy.service in /etc/systemd/system
[Unit]
Description=nginx-proxy.service
After=docker.service
Requires=docker.service

[Service]
TimeoutStartSec=0
ExecStartPre=-/usr/bin/docker kill nginx-proxy
ExecStartPre=-/usr/bin/docker rm nginx-proxy
ExecStartPre=-/usr/bin/docker pull jwilder/nginx-proxy
ExecStartPre=-/usr/bin/docker network create nginx-proxy
ExecStart=/usr/bin/docker run -p 80:80 -p 443:443 \
  -v /var/run/docker.sock:/tmp/docker.sock:ro  \
  -v /home/core/certificates:/etc/nginx/certs:ro \
  -v /home/core/vhost.d:/etc/nginx/vhost.d:ro \
  -v /home/core/conf.d/external.conf:/etc/nginx/conf.d/external.conf \
  -v /usr/share/nginx/html \
  --net=nginx-proxy \
  --label com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy \
  --name nginx-proxy \
  jwilder/nginx-proxy
ExecStop=/usr/bin/docker stop nginx-proxy

[Install]
WantedBy=multi-user.target
  1. Connect certbot container to nginx-proxy container
Description=certbot.service
After=nginx-proxy.service
Requires=nginx-proxy.service

[Service]
TimeoutStartSec=0
ExecStartPre=-/usr/bin/docker kill certbot
ExecStartPre=-/usr/bin/docker rm certbot
ExecStartPre=/usr/bin/docker pull jrcs/letsencrypt-nginx-proxy-companion
ExecStart=/usr/bin/docker run \
  -v /var/run/docker.sock:/var/run/docker.sock:ro \
  -v /home/core/certificates:/etc/nginx/certs:rw \
  -v /home/core/vhost.d:/etc/nginx/vhost.d \
  --net=nginx-proxy \
  --volumes-from nginx-proxy \
  --name certbot \
  jrcs/letsencrypt-nginx-proxy-companion

[Install]
WantedBy=multi-user.target
  1. /etc/systemd/system/itservice.service
[Unit]
Description=itservice
After=nginx-proxy.service
Requires=nginx-proxy.service

[Service]
TimeoutStartSec=0
Type=simple
WorkingDirectory=/home/core/itservice
ExecStart=/opt/bin/docker-compose -f /home/core/itservice/docker-compose.yml -f /home/core/itservice/docker-compose.override.yml up
ExecStop=/opt/bin/docker-compose -f /home/core/itservice/docker-compose.yml -f /home/core/itservice/docker-compose.override.yml stop

[Install]
WantedBy=multi-user.target

It’s important to have docker-compose.yml version 2+ and connect frontend networks like this:

version: "2"
services: 
  app:
    image: myapp
  networks:
     - frontend
networks: 
  - frontend
     external:
        name: nginx-proxy

In this way container should be accessible to nginx-proxy right when you do

docker-compose up

.