nginx使用自签CA证书(docker-compose启动nginx容器,https访问nginx)
前言
以容器为例,说明nginx自签CA证书的使用。
目录结构如下:
[root@n9e-client-01 nginx]# tree ./
./
├── build
│ └── index.html
├── cert
│ ├── server.crt
│ └── server.key
├── docker-compose.yml
└── nginx.conf
1. nginx.conf
https监听443 端口,http监听80端口并转到 443端口
# gzip设置
gzip on;
gzip_vary on;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_min_length 1000;
gzip_proxied any;
gzip_disable "msie6";
#gzip_http_version 1.0;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;
server {
listen 443 ssl;
server_name web443;
ssl_certificate /etc/nginx/cert/server.crt;
ssl_certificate_key /etc/nginx/cert/server.key;
ssl_session_timeout 5m;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
add_header Cache-Control no-store;
}
}
server {
listen 80;
server_name web80;
rewrite ^(.*)$ https://$host$1 permanent;
}
2. docker-compose.yml
version: "3"
services:
nginx-01:
image: "harbocto.boe.com.cn/public/nginx:1.21"
restart: on-failure
ports:
- 80:80
- 443:443
volumes:
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
- ./build:/usr/share/nginx/html
- ./cert:/etc/nginx/cert
restart: always
3. 证书文件
在 cert目录下放置证书文件,如目录结构中所示。
如果要使用自签证书,创建方法见《openssl制作CA自签证书》
4. build目录
容器挂载的前端静态文件
在 index.html中随便写些内容:
[root@n9e-client-01 nginx]# cat build/index.html
hello world
5. 启动和查看
- 启动nginx
[root@n9e-client-01 nginx]# docker-compose up -d
Creating network "nginx_default" with the default driver
Creating nginx_nginx-01_1 ... done
[root@n9e-client-01 nginx]# docker-compose ps
Name Command State Ports
----------------------------------------------------------------------------------------------------
nginx_nginx-01_1 /docker-entrypoint.sh ngin ... Up 0.0.0.0:443->443/tcp, 0.0.0.0:80->80/tcp