Nginx and Let’s Encrypt with Docker in Less Than 5 Minutes

Getting Nginx to run with Let’s Encrypt in a docker-compose environment is trickier than you’d think …

Quick Reminder: What is docker-compose?

With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration

The Setup

version: '3'
services:
nginx:
image: nginx:1.15-alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./data/nginx:/etc/nginx/conf.d
certbot:
image: certbot/certbot
server {
listen 80;
server_name example.org;
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name example.org;

location / {
proxy_pass http://example.org; #for demo purposes
}
}

Linking up nginx and certbot

- ./data/certbot/conf:/etc/letsencrypt
- ./data/certbot/www:/var/www/certbot
volumes:
- ./data/certbot/conf:/etc/letsencrypt
- ./data/certbot/www:/var/www/certbot
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
ssl_certificate /etc/letsencrypt/live/example.org/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.org/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

The Chicken or the Egg?

curl -L https://raw.githubusercontent.com/wmnnd/nginx-certbot/master/init-letsencrypt.sh > init-letsencrypt.sh

Automatic Certificate Renewal

entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'"
command: "/bin/sh -c 'while :; do sleep 6h & wait $${!}; nginx -s reload; done & nginx -g \"daemon off;\"'"

Docker-compose Me Up!

Are you interested in best practices for application deployment? Make sure to subscribe to my newsletter!

I make software. Passionate about Elixir. User of C++, Ruby & JavaScript. Current project: https://www.dblsqd.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store