Use Let's Encrypt with Certbot and nginx inside Docker

Update 8 Jun 2019: Change crontab certbot renew command to use --deploy-hook instead of --renew-hook.

Using certbot to install and auto-renew Let’s Encrypt SSL certs with nginx installed in system is almost fool-proof. How about nginx inside docker? Not so easy.

Assume we use the official nginx docker imageand start the docker container with name my_nginx.

docker run -d -p 80:80 -p 443:443 -v /var/www:/var/www -v /etc/letsencrypt:/etc/letsencrypt --name my_nginx nginx

Assuming the domain name is www.example.com.

nginx config:

http {
  server {
    listen 443 ssl;
    server_name     www.example.com;

    ssl_certificate    /etc/letsencrypt/live/www.example.com/fullchain.pem;
    ssl_certificate_key    /etc/letsencrypt/live/www.example.com/privkey.pem;

    location / {
        proxy_pass      https://172.17.0.1:444;  # the backend server
    }
  }

  server {
    listen 80;
    server_name www.example.com;
    location /.well-known {
      alias /var/www/www.example.com/.well-known;
    }
  }
}

Run certbot on the host system to generate the required assets for verification.

sudo certbot certonly --webroot -w /var/www/www.example.com/ -d www.example.com

Tell nginx inside docker to reload the cert.

docker exec -it my_nginx nginx -s reload

Try renewing the cert.

sudo certbot renew --force-renew --renew-hook "docker exec -it my_nginx nginx -s reload"

Insert this line to crontab -e for auto-renewal.

47 4,16   * * *   root   certbot renew --quiet --deploy-hook "docker exec -it my_nginx nginx -s reload"
Tags// , , ,