Setup SSL for Nginx Docker container with Let’s Encrypt, Certbot

Hello, Today We are going to set up SSL for nginx docker container with Free SSL (Let’s Encrypt / Certbot) and also with auto-renewal. Let’s Encrypt certificates will expire in 3 months and need to be renewed after the certificate expires. So, there is a script for renewal automatically in crontab.

Nginx Docker Setup

Execute this docker command to run the Nginx container with host network interface and mounted volumes. Note: This will create “nginx” directory in current path.

docker run --name nginx --net=host -v nginx/html:/usr/share/nginx/html -v nginx/certs:/certs -v nginx/etc:/etc/nginx --restart always -d nginx:latest

Add this configuration in nginx conf file to allowing the certbot access for verification.

location ^~ /.well-known/acme-challenge { root /usr/share/nginx/html; }

Certbot Setup for SSL

This step is the one time process. And this step is not required for renewal. And we’re going to run this step in the container so no pollution in the environment :-).

If it gets failed, then mostly the certbot is unable to access the acme-challenge file. So check in nginx config for access.

docker run --rm -it -v nginx/certs:/etc/letsencrypt -v nginx/html:/html certbot/certbot certonly --webroot -w /html -d www.example.com -d example.com

Also run this command to changing the permissions in SSL certificates for nginx access.

sudo chown $USER:$USER -Rf nginx/certs

SSL Auto-renewal with Certbot

This docker command will do the check for renewal if the certificate is eligible for renewal, then it will update the certificate automatically.

Set this command in cronjob to do renewal automatically without any manual touch.

Note: Give correct path in volumes parameter when you set in cron.

docker run --rm -it -v nginx/certs:/etc/letsencrypt -v nginx/html:/html certbot/certbot renew --webroot -w /html && sudo chown $USER:$USER -Rf nginx/certs/

For Example:

This will get execute at every Monday on crontab.

0 0 * * 1 /usr/bin/docker run --rm -it -v ~/example/nginx/certs:/etc/letsencrypt -v ~/example/nginx/html:/html certbot/certbot renew --webroot -w /html && sudo chown $USER:$USER -Rf nginx/certs/

That’s all good to go. Without polluting the environment and any manual touch. This makes east for setup and auto-renewal SSL certificate in nginx with docker container.

For beginners to run nginx docker container with mounted volumes. Please visit Link

Leave a Reply

Your email address will not be published. Required fields are marked *