使用 mkcert 生成内网可信 SSL 证书,配合 Nginx Docker 容器实现 HTTPS 访问。
本文环境:Arch Linux。
安装 mkcert
1 2
| sudo pacman -Syu sudo pacman -S mkcert
|
创建所需文件(放在同一目录)
docker-compose.yml
1 2 3 4 5 6 7 8 9 10 11 12
| services: nginx: image: nginx:1.25 container_name: nginx-ssl ports: - "80:80" - "443:443" volumes: - ./html:/usr/share/nginx/html - ./certs:/etc/ssl/certs - ./nginx/conf.d:/etc/nginx/conf.d restart: unless-stopped
|
init.sh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| #!/bin/bash
LOCAL_IP="192.168.1.102" HOSTNAMES=("localhost" "127.0.0.1" "$LOCAL_IP")
mkdir -p html certs nginx/conf.d
if [ ! -f html/index.html ]; then cat << 'HTMLEOF' > html/index.html <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>nginx HTTPS 测试</title> </head> <body> <h1>Nginx HTTPS 成功运行!</h1> </body> </html> HTMLEOF fi
if [ ! -f certs/server.crt ] || [ ! -f certs/server.key ]; then echo "生成自签证书..." mkcert -cert-file certs/server.crt -key-file certs/server.key "${HOSTNAMES[@]}" fi
if [ ! -f nginx/conf.d/default.conf ]; then cat << 'CONFEOF' > nginx/conf.d/default.conf server { listen 80; server_name localhost $LOCAL_IP; return 301 https://$host$request_uri; }
server { listen 443 ssl; server_name localhost $LOCAL_IP;
ssl_certificate /etc/ssl/certs/server.crt; ssl_certificate_key /etc/ssl/certs/server.key;
location / { root /usr/share/nginx/html; index index.html; } } CONFEOF fi
echo "html、证书和 nginx 配置已生成完毕"
|
generate-cert.sh
1 2 3 4
| #!/bin/bash
openssl x509 -outform der -in ~/.local/share/mkcert/rootCA.pem -out rootCA.crt cp ~/.local/share/mkcert/rootCA.pem .
|
运行步骤
- 运行
bash init.sh 初始化目录并生成证书
- 启动 Docker 容器:
docker-compose up -d
- 运行
bash generate-cert.sh 导出客户端证书
客户端安装证书
- Windows:将
rootCA.crt 拷到 Windows 上双击安装(选择「当前用户」)
- Linux:
rootCA.pem 按发行版方式安装(不同发行版安装 CA 证书方式不同)
验证
访问 https://<服务器IP>,浏览器应显示连接安全。