Docker Nginx 整合 Certbot 替網站加上 Let’s Encrypt SSL,並排程自動更新憑證

環境

docker hub:nginx:latest

更新apt-get

apt-get update -y

下載 Certbot

apt-get install certbot python3-certbot-nginx -y

取得 SSL Certificate

因Let’s Encrypt憑證在一定時間內申請會有次數限制,Certbot有提供『–dry-run』指令讓憑證的申請可以先在測試環境進行測試,雖然測試環境也有次數限制,但提供憑證申請的次數更多,故可以先找出憑證申請失敗的原因,並將其改善,及再次使用測試環境申請確定沒問題後,才使用一般方式申請憑證。

certbot certonly --nginx --email xx@gmail.com --agree-tos -d tsslwordpress-xx.xx --dry-run

成功話就出現Simulating a certificate request for xx.xx The dry run was successful.

certbot certonly --nginx --email xx@gmail.com --agree-tos -d tsslwordpress-xx.xx

詢問你是否需要收到Let’s Encrypt組織相關的郵件
Would you be willing, once your first certificate is successfully issued, to
share your email address with the Electronic Frontier Foundation, a founding
partner of the Let’s Encrypt project and the non-profit organization that
develops Certbot? We’d like to send you email about our work encrypting the web,
EFF news, campaigns, and ways to support digital freedom.
(Y)es/(N)o: n

申請成功出現Account registered.Requesting a certificate for tsslwordpress-xx.xx

設定nginx

server {
	listen 443 ssl;
	listen [::]:443 ssl;
	server_name tsslwordpress-xx.xx;
	
	ssl_certificate     /etc/letsencrypt/live/tsslwordpress-xx.xx/fullchain.pem;
	ssl_certificate_key /etc/letsencrypt/live/tsslwordpress-xx.xx/privkey.pem;
	ssl_trusted_certificate /etc/letsencrypt/live/tsslwordpress-xx.xx/chain.pem;
	ssl_protocols       TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
	ssl_ciphers TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-GCM-SHA256:TLS13-AES-128-CCM-8-SHA256:TLS13-AES-128-CCM-SHA256:EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+ECDSA+AES128:EECDH+aRSA+AES128:RSA+AES128:EECDH+ECDSA+AES256:EECDH+aRSA+AES256:RSA+AES256:EECDH+ECDSA+3DES:EECDH+aRSA+3DES:RSA+3DES:!MD5;
	ssl_prefer_server_ciphers on;
	ssl_session_timeout 5m;
	ssl_session_cache shared:SSL:5m;

	location / {
	  ..省略
	}
}
nginx -s reload

自動更新憑證

由於 Let’s Encrypt 憑證簽發為每三個月一次,也就是每 90 天必須更新(renew)一次,我們可以藉由 crontab 設置排程工作定期幫我們更新 SSL 憑證。

可以輸入下列指令 dry run 一下,確認更新憑證沒有問題。

certbot renew --dry-run

Congratulations, all simulated renewals succeeded:
/etc/letsencrypt/live/tsslwordpress-xx.xx/fullchain.pem (success)

安裝排程

apt-get -y install cron
apt-get -y install vim
crontab -e

0 1 * * 1 /usr/bin/certbot renew –quiet
每個禮拜1早上1點執行

確認憑證狀態

certbot certificates

Found the following certs:
Certificate Name: tsslwordpress-xx.xx
Serial Number: 333c26bc09e8154e44572075b57888e00d3
Key Type: ECDSA
Domains: tsslwordpress-xx.xx
Expiry Date: 2024-02-19 01:42:29+00:00 (VALID: 89 days)
Certificate Path: /etc/letsencrypt/live/tsslwordpress-xx.xx/fullchain.pem
Private Key Path: /etc/letsencrypt/live/tsslwordpress-xx.xx/privkey.pem

Leave a Comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *