Docker-Compose部署中Certbot与Nginx循环依赖问题求助
解决Docker Compose中Nginx与Certbot的循环依赖问题(AWS EC2 Amazon Linux 2环境)
核心思路是先启动仅支持ACME验证的临时Nginx配置,让Certbot完成域名认证并生成证书,再切换到包含HTTPS配置的生产Nginx配置,打破循环依赖。
1. 准备Nginx双配置文件
创建两个Nginx配置文件,分别用于证书获取阶段和生产阶段:
临时验证配置 nginx-temp.conf
仅处理ACME挑战请求,不涉及HTTPS:
server { listen 80; server_name api.ch.com; # 处理Certbot的ACME验证请求 location /.well-known/acme-challenge/ { root /var/www/certbot; } # 临时将其他80端口请求重定向(证书生成后生效) location / { return 301 https://$host$request_uri; } }
生产配置 nginx-prod.conf
包含完整HTTPS配置,依赖Certbot生成的证书:
server { listen 80; server_name api.ch.com; # 所有HTTP请求重定向到HTTPS return 301 https://$host$request_uri; } server { listen 443 ssl; server_name api.ch.com; ssl_certificate /etc/letsencrypt/live/api.ch.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/api.ch.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # 反向代理到你的Node.js应用 location / { proxy_pass http://node-app:3000; # 替换为你的Node服务名称和端口 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; } }
2. 编写Docker Compose配置
调整docker-compose.yml,让Nginx和Certbot共享验证目录,支持临时配置切换:
version: '3.8' services: node-app: # 你的Node.js应用配置 build: ./node-app restart: unless-stopped # 其他配置(环境变量、端口等) postgres: # 你的Postgres配置 image: postgres:15-alpine restart: unless-stopped # 其他配置(卷、环境变量等) redis: # 你的Redis配置 image: redis:alpine restart: unless-stopped # 其他配置 nginx: image: nginx:alpine ports: - "80:80" - "443:443" volumes: - ./nginx-temp.conf:/etc/nginx/conf.d/default.conf - ./certbot/conf:/etc/letsencrypt - ./certbot/www:/var/www/certbot restart: unless-stopped depends_on: - node-app certbot: image: certbot/certbot volumes: - ./certbot/conf:/etc/letsencrypt - ./certbot/www:/var/www/certbot command: certonly --webroot -w /var/www/certbot --email your-email@example.com --agree-tos --no-eff-email -d api.ch.com
3. 自动化部署脚本
创建deploy.sh脚本,一键完成证书获取、配置切换和服务重启:
#!/bin/bash # 创建Certbot所需目录 mkdir -p ./certbot/conf ./certbot/www # 启动临时Nginx服务 docker-compose up -d nginx # 运行Certbot获取证书 docker-compose run --rm certbot # 替换为生产Nginx配置 cp ./nginx-prod.conf ./nginx-temp.conf # 重启Nginx应用新配置 docker-compose restart nginx
给脚本添加执行权限:
chmod +x deploy.sh
4. 后续证书自动续签
添加定时任务,每周自动续签证书并重启Nginx:
# 编辑crontab配置 crontab -e # 添加以下内容(每周一凌晨0点执行) 0 0 * * 1 cd /path/to/your/project && docker-compose run --rm certbot renew && docker-compose restart nginx
注意事项
- 确保域名
api.ch.com已正确解析到EC2实例的公网IP - 确认EC2安全组已开放80、443端口(你已完成此步骤)
- 第一次运行脚本时,Certbot会自动生成证书,后续续签无需手动干预
内容的提问来源于stack exchange,提问作者PirateApp
相关产品推荐
相关产品推荐

