Docker部署Nginx容器80端口自动转443端口
2021-09-24
前些天设置了Nginx反向代理,发现当时没有设置443端口,导致https不能访问,今天抽时间重新设置了下。
首先把之前的容器删除掉,原因是我在80基础上增加443端口的时候报错了,暂时没有找到解决方案,索性直接删除了,重新创建一个。当然如果你有更好的办法可以不删除。也请留言告诉我,我也好再学习下。
那么我们开始啦
拉取nginx镜像
docker pull nginx
运行nginx容器config用于拷贝nginx配置文件
docker run --name nginxconfig -d docker.io/nginx
docker cp nginxconfig:/etc/nginx/ /root/
删除
docker stop nginxconfig
docker rm nginxconfig
创建服务nginx容器
docker run --name nginx -p 80:80 -p 443:443 -v /root/nginx/:/etc/nginx/ -d docker.io/nginx
- 映射端口443,用于https请求
- 映射端口80,用于http请求
配置如下(不做修改)
拷贝申请的腾讯云ssl证书(其他的也可以阿里云等)
配置http自动跳往https
server {
server_name loveblog.vip; #域名
listen 80; #监听80端口
rewrite ^(.*) https://$server_name$1 permanent; #${server_name}可以换成$host
} #设置http自动跳转https
server {
listen 443 ssl; #监听443端口
server_name loveblog.vip; #域名
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
# 增加ssl
ssl on; #如果强制HTTPs访问,这行要打开
ssl_certificate /etc/nginx/certs/1_www.loveblog.vip_bundle.crt;
ssl_certificate_key /etc/nginx/certs/2_www.loveblog.vip.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_protocols SSLv2 SSLv3 TLSv1.2; # 指定密码为openssl支持的格式
ssl_ciphers HIGH:!aNULL:!MD5; # 密码加密方式
ssl_prefer_server_ciphers on; # 依赖SSLv3和TLSv1协议的服务器密码将优先于客户端密码
location / { # 定义首页索引目录和名称
proxy_pass http://81.70.166.11:8090;
proxy_redirect default;
}
#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 { #重定向错误页面到 /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;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
根据自己的域名和证书地址配置然后保存配置
重启容器
docker restart nginx
查看下是否重启成功
docker ps -a
打开浏览器测试
至此,设置成功,可以愉快了的写博客了。