在 Gunicorn 中配置 Let’s Encrypt 证书自动更新,您需要结合使用 Certbot 工具和系统的定时任务功能(如 cron)。以下是详细步骤:

步骤 1:安装 Certbot

根据您的操作系统,使用以下命令安装 Certbot:

Ubuntu/Debian:
sudo apt update && sudo apt install certbot python3-certbot-nginx
CentOS/RHEL:
sudo yum install epel-release
sudo yum install certbot python3-certbot-nginx
Fedora:
sudo dnf install certbot python3-certbot-nginx

步骤 2:获取 Let’s Encrypt 证书

使用 Certbot 获取证书,同时配置 Nginx 进行自动续期(即使 Gunicorn 不直接处理 HTTPS,仍需 Nginx 作为反向代理):

sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

步骤 3:配置 Nginx 反向代理

编辑 Nginx 配置文件,将流量从 Nginx 转发到 Gunicorn:

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name yourdomain.com www.yourdomain.com;

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

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

步骤 4:设置自动续期

编辑当前用户的 crontab 文件:

crontab -e

添加以下行,每天凌晨 2 点自动检查并续期证书:

0 2 * * * /usr/bin/certbot renew --quiet && systemctl reload nginx

步骤 5:重载 Nginx 配置

使新的定时任务生效:

sudo systemctl reload nginx

注意事项

  • 防火墙设置:确保防火墙开放 80 和 443 端口。
  • 证书路径:确保证书路径正确,与 Nginx 配置中的一致。
  • Gunicorn 启动:Gunicorn 应监听 Nginx 转发的端口(如 8000),无需处理 HTTPS。

总结

  • Certbot 负责证书的获取和自动续期
  • Nginx 作为反向代理处理 HTTPS 请求,并转发给 Gunicorn
  • cron 定时任务确保证书在到期前自动更新

通过以上步骤,您的 Gunicorn 应用程序将通过 Nginx 使用自动更新的 Let’s Encrypt 证书,保障网站安全。

在这里插入图片描述

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐