Enabling SSL with Let’s Encrypt, NGINX and Docker

Recently, I read a lot of articles on how to enable ssl with certbot, nginx and docker, but all the methods I read did not work for me untill I found this methods listed below. Thanks to all the authories who wrote the articles in the references.

Steps

  • Setting up Nginx and Certbot on your host server
  • Obtaining an SSL Certificate on your hose server
  • Map your host letsencrypt folder to nginx in docker

Detail

Step 1 Setting up Nginx and Certbot on your host server

$ sudo apt-get update
$ sudo apt-get install software-properties-common
$ sudo add-apt-repository ppa:certbot/certbot
$ sudo apt-get update
$ sudo apt-get install python-certbot-nginx certbot nginx

Setting up Nginx

$ sudo vim /etc/nginx/sites-available/default

find the following line:

server_name localhost;

change to your domain name

server_name example.com www.example.com;

reload your nginx new configuration

$ sudo nginx -t
$ sudo service nginx reload

Step 2 Obtaining an SSL Certificate

$ sudo certbot --nginx -d example.com -d www.example.com

You need to configure your HTTPS settings according to certbot.

After you configure your HTTPS, stop the nginx

$ sudo service nginx stop

Step 3 Map your host letsencrypt folder to nginx in docker

You’d like to modify your nignx config file first.

server {
  listen 443 ssl http2;
  server_name app1;

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

  # ... The rest of your NGINX configuration.
}

server {
  listen 80;
  server_name app1.com;
  return 301 https://$host$uri; # redirect http to https
}

Then you need to open 443 port and map folders to docker.

Here is a sample.

version: '2'
services:
   nginx:
    image: nginx:latest
    ports:
        - '80:80'
        - '443:443'  # don't forget to open 443 port
    volumes:
        - ./nginx:/etc/nginx/conf.d
        - ./logs/nginx:/var/log/nginx
        - ./wordpress:/var/www/html
        - /etc/letsencrypt:/etc/letsencrypt # you need to map this folder
        - /etc/ssl:/etc/ssl # you need to map this folder as well
    links:
        - wordpress
    restart: always
    container_name: qinjingfei_nginx

Conclusion

I knew this approach is not elegant, but it works.

References

如何免费的让网站启用HTTPS

How To Secure Nginx with Let’s Encrypt on Ubuntu 14.04

Enabling SSL with Let’s Encrypt, NGINX and Docker

stackoverflow

发表评论

电子邮件地址不会被公开。 必填项已用*标注