1 前置设置
# 获取nginx 1.15版本镜像(版本自行替换吧)
docker pull nginx:1.15
# 创建nginx挂在目录
mkdir -p {/data/nginx/{logs,cert}}
# 跑起nginx容器,用于获取配置文件
docker run --name nginx -d nginx:1.15
# 拷贝nginx配置文件
docker cp nginx:/etc/nginx/conf.d /data/nginx
docker cp nginx:/etc/nginx/nginx.conf /data/nginx
# 删除容器
docker stop nginx && docker rm nginx
2 生成ssl证书
cd /data/nginx/cert
# 生成私钥
openssl genrsa -out nginx.key
#生成证书(公钥)
openssl req -new -x509 -key nginx.key -out nginx.crt
ps:可以使用免费的let's encrypt证书,也可以使用云服务商提供的证书
3 配置https
# 编辑配置文件
vim /data/nginx/conf.d/
配置文件内容(需要修改部分已备注)
server {
listen 80;
server_name localhost; # 换成自己的host
# http请求重定向到https上
rewrite ^(.*)$ https://${server_name}$1 permanent;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
#eeee
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# 增加https部分设置
server {
listen 443 ssl;
server_name localhost; # 换成自己的host
ssl_certificate /etc/nginx/cert/nginx.crt; #指定证书位置(通过目录挂载到容器内部)
ssl_certificate_key /etc/nginx/cert/nginx.key; #指定私钥位置(通过目录挂载到容器内部)
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
4 启动nginx
docker run --name nginx -d \
-p 80:80 \
-p 443:443 \
-v /data/nginx/cert:/etc/nginx/cert \
-v /data/nginx/nginx.cof:/etc/nginx/nginx.conf \
-v /data/nginx/conf.d:/etc/nginx/conf.d \
nginx:1.15
5 测试访问
通过80端口访问,自动跳转到https的443端口