Docker环境下在宿主机环境中通过CertBot获取ssl证书,并将证书关联到Docker下的Nginx服务器上

Docker环境下在宿主机环境中通过CertBot获取ssl证书,并将证书关联到Docker下的Nginx服务器上

    我的服务器中的所有服务包括nginx都是通过Docker安装的,而Certbot一般是安装到宿主机上的,所以在宿主机上直接安装Certbot,并且通过Certbot获取SSL证书是会报如下的错误的:

The nginx plugin is not working; there may be problems with your existing configuration.
The error was: NoInstallationError("Could not find a usable 'nginx' binary. Ensure nginx exists, the binary is executable, and your PATH is set correctly.",)

    因为Certbot会首先检测服务器中是否包含Nginx实例,镜像与宿主机环境是隔离的,所以Certbot是无法直接在线安装SSL证书的。不过可以换一种方法解决这个问题,下面是我的实际操作步骤,大家可以参考。

第一、安装Certbot:

首先,确保 EPEL (Extra Packages for Enterprise Linux) 仓库已启用,因为 Certbot 及其插件通常可以从那里获取:

sudo yum install epel-release

然后安装 Certbot 和 Nginx 插件(如果您打算使用 Nginx 插件):

sudo yum install certbot python2-certbot-nginx

请注意,在较新的环境中,Python 3 是默认的 Python 版本,但在 RHEL/CentOS 7 中,默认是 Python 2。如果你的系统中有 Python 3,并且你希望使用它,那么你需要安装 python3-certbot-nginx 而不是 python2-certbot-nginx

第二、获取证书

如果您的 Nginx 运行在一个 Docker 容器中,您应该使用 Webroot 插件来获取证书,而不是 Nginx 插件。这是因为 Nginx 插件需要直接访问宿主机上的 Nginx 配置文件,而 Docker 化的应用程序中 Nginx 是在容器内运行的。

假设你的 Nginx 容器中的 webroot 路径为 /usr/share/nginx/html,你可以这样做:

1、修改 Docker Compose 文件或 Docker 运行命令 来挂载 webroot 目录到宿主机的一个目录下,例如 /Users/Document/ssl

- /Users/Document/ssl:/usr/share/nginx/html             # 挂载webroot路径与宿主机对应
- /etc/letsencrypt:/etc/letsencrypt              # 挂载Certbot证书路径

2、运行 Certbot 命令 来获取证书,使用挂载到宿主机的路径作为 webroot:

sudo certbot certonly --webroot -w /Users/Document/ssl -d yourdomain.com -d www.yourdomain.com

第三、Nginx 配置证书

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    # 关键点
    location /.well-known/acme-challenge/ {
        root /usr/share/nginx/html;
        default_type "text/plain";
        try_files $uri =404;
    }

    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;  
      
    # 更多 SSL 设置...    
    # 其他 location 块...
}

第四、自动续订证书

1、运行 crontab -e 打开 crontab 文件。

2、在新行中添加以下命令:

0 2 * * * /usr/bin/certbot renew --webroot --webroot-path=/Users/Document/ssl --quiet && /bin/systemctl reload nginx

3、为了确保 cron 作业按预期工作,你可以手动测试证书续订过程:

/usr/bin/certbot renew --dry-run

这条命令会模拟一次续订过程,但不会实际更改任何证书。如果一切正常,你应该看到类似“Congratulations, all renewals succeeded”的消息。

总结

以上便是在Docker环境中通过Certbot生成SSL证书的全过程,其实除了在宿主机上生成SSL方式外还可以在Docker镜像中生成,我感觉在宿主机上生成的方式更直观简单。以上是我的实际操作步骤,希望可以帮到大家!