You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Docker NGINX官方镜像中安装Certbot?

在NGINX官方Docker镜像中配置Certbot的正确方案

为什么你之前的Snap方法行不通

官方NGINX镜像基于Debian/Alpine轻量系统,默认未运行systemd,而Snap包管理依赖systemd提供的服务管理能力,因此必然会出现无法连接snapd的错误,这条路从一开始就不适合容器环境。


方案一:使用Certbot独立Docker容器(推荐,职责分离)

将Certbot与NGINX容器分离,通过共享挂载目录实现证书管理,避免依赖冲突:

获取证书

  1. 临时停止正在运行的NGINX容器(释放80/443端口用于ACME验证):
docker stop your-nginx-container
  1. 运行Certbot容器获取证书:
docker run -it --rm \
  -v "/etc/letsencrypt:/etc/letsencrypt" \
  -v "/var/lib/letsencrypt:/var/lib/letsencrypt" \
  -v "/var/www/html:/var/www/html" \
  certbot/certbot certonly --webroot -w /var/www/html -d your-domain.com
  • /var/www/html需与NGINX容器的网页根目录保持一致,用于完成HTTP-01验证
  • 替换your-domain.com为你的实际域名
  1. 重启NGINX容器,确保配置文件已指向/etc/letsencrypt下的证书文件

证书续期

直接运行Certbot容器执行续期命令,无需停止NGINX(续期时会自动完成验证):

docker run -it --rm \
  -v "/etc/letsencrypt:/etc/letsencrypt" \
  -v "/var/lib/letsencrypt:/var/lib/letsencrypt" \
  -v "/var/www/html:/var/www/html" \
  certbot/certbot renew --webroot -w /var/www/html

可将此命令加入宿主机的Cron定时任务,实现自动续期。


方案二:在NGINX镜像中直接安装Certbot(单容器模式)

如果必须将Certbot与NGINX放在同一容器内,可通过APT安装而非Snap:

构建自定义NGINX镜像

创建Dockerfile:

FROM nginx:latest

# 安装Certbot及NGINX插件
RUN apt update && \
    apt install -y certbot python3-certbot-nginx && \
    rm -rf /var/lib/apt/lists/*

# 复制你的NGINX配置文件(需提前配置证书占位路径)
COPY your-nginx-config.conf /etc/nginx/conf.d/default.conf

构建镜像:

docker build -t nginx-with-certbot .

获取证书与运行

  1. 运行容器并挂载证书目录到宿主机:
docker run -d \
  -p 80:80 -p 443:443 \
  -v "/etc/letsencrypt:/etc/letsencrypt" \
  -v "/var/www/html:/var/www/html" \
  --name nginx-with-certbot \
  nginx-with-certbot
  1. 进入容器执行证书获取命令:
docker exec -it nginx-with-certbot certbot --nginx -d your-domain.com

证书续期

直接在容器内执行续期命令:

docker exec nginx-with-certbot certbot renew

同样可通过宿主机Cron定时执行此命令。


内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 17:27:21