docker-compose搭建nginx,并验证https是否生效

时间:2025-03-31 18:42:57

使用docker-compose搭建nginx

  1. 创建文件夹
mkdir -p /opt/docker/nginx/certs /opt/docker/nginx/conf
cd /opt/docker/nginx
  1. 将ssl证书文件导入到certs目录下

  2. 编写核心配置文件default

cd /opt/docker/nginx/conf
vim 
#向导入以下脚本

注意 # 的注释

server {
        listen 443 ssl; 
        # xxx 要代理的https域名
        # server_name xxx;
        server_name 
        # 后缀为crt文件名称
        ssl_certificate  /certs/xxxxx.com_bundle.crt;
        # 后缀为key文件名称
        ssl_certificate_key /certs/;
        ssl_session_timeout 5m;
        ssl_protocols TLSv1.2 TLSv1.3; 
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE; 
        ssl_prefer_server_ciphers on;
        location / {
            root html; 
            # 转发的ip:port
            # proxy_pass http://ip:port;
            proxy_pass http://192.168.3.20:9878;
            index   ;
        }
    }
server {
    listen 80;
    # xxx 代理的https域名
    # server_name xxx;
    server_name 
    return 301 https://$host$request_uri; 
}
  1. 编写
version: "3"
services:
   nginx:
     image: nginx:1.18.0
     ports:
       - 80:80
       - 443:443
     volumes:
       - ./certs:/certs
       - ./conf/:/etc/nginx//
       - /etc/localtime:/etc/localtime
     restart: always
     container_name: nginx
     environment:
       - TZ=Asia/Shanghai
       - LANG=en_US.UTF-8
  1. 创建nginx容器
docker-compose -f  up -d
  1. 验证nginx配置的https是否成功
# 以 转发192.168.3.20:9878为例
# 1. 验证http://192.168.3.20:9878是否可用
# 2. 验证:9878是否可用
# 3. 验证是否可用

#注意http有端口,而https无端口
# 结合nginx日志查看更有效
docker logs nginx -f --tail 100