Docker部署Nginx和配置https

Docker部署Nginx和配置https

Nginx部署过程

sh 复制代码
# 防火墙开放需要使用的端口
firewall-cmd --zone=public --add-port=80/tcp --permanent
# 重新加载
firewall-cmd --reload

# 拉取nginx镜像
docker pull nginx:1.18.0
# 创建挂载目录
mkdir -p /root/nginx/conf
mkdir -p /root/nginx/log
mkdir -p /root/nginx/html
# 生成容器,将生成的配置文件等复制到挂载目录
docker run --name nginx -p 80:80 -d nginx:1.18.0
docker cp nginx:/etc/nginx/nginx.conf /root/nginx/conf/nginx.conf
docker cp nginx:/etc/nginx/conf.d /root/nginx/conf/conf.d
docker cp nginx:/usr/share/nginx/html /root/nginx/

# 然后删除当前容器,最后挂载目录运行
# -u root 以root用户运行容器,非必须
# --privileged=true 给于容器访问挂载目录的权限
docker rm -f nginx
docker run \
-u root --privileged=true \
-p 80:80 \
--restart=always \
--name nginx \
-v /root/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
-v /root/nginx/conf/conf.d:/etc/nginx/conf.d \
-v /root/nginx/log:/var/log/nginx \
-v /root/nginx/html:/usr/share/nginx/html \
-d nginx:1.18.0

配置https

nginx使用https,需要一个SSL/TLS证书,有几种方式可以获得证书:

  • 从证书颁发机构(CA)购买:如Symantec, GoDaddy, Let's Encrypt等。
  • 使用Let's Encrypt的免费证书:Let's Encrypt是一个提供免费、自动化和开源证书的证书颁发机构(CA)。你可以使用Certbot等工具自动获取和续订证书。
  • 使用openssl生成自签证书。

这里使用第三种方式。

sh 复制代码
# 生成私钥
openssl genrsa -out privatekey.pem 2048
# 证书签名请求:一路回车,但Common Name需要填入你的服务器 IP或者域名
openssl req -new -key privatekey.pem -out private-csr.pem
# 自签名并创建证书
openssl x509 -req -days 365 -in private-csr.pem -signkey privatekey.pem -out certificate.pem

# 注意:docker部署时,需要把证书文件放入容器内,用容器内的地址读取
# 复制证书文件到容器内
docker cp privatekey.pem nginx:/xxx/xxx/
docker cp certificate.pem nginx:/xxx/xxx/
# 进入容器
docker exec -it nginx bash

# 可以将证书导入到本地解决浏览器提示不安全:win+r -> certmgr.msc,将证书导入到"个人->证书"里

然后在/root/nginx/conf/conf.d/下面创建一个xxx.conf文件,内容如下:

复制代码
nginx
~~~nginx
server {
    listen 433 ssl;

    ssl_certificate     /xxx/xxx/certificate.pem;
    ssl_certificate_key  /xxx/xxx/privatekey.pem;
    location / {
        proxy_pass  http://127.0.0.1:3000;
        proxy_set_header Host $proxy_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

最后docker restart nginx就大功搞成了。

相关推荐
Patrick_Wilson1 天前
从「改个端口」到 502:Next.js on k8s 的容器端口、Service 映射与 env 覆盖
docker·kubernetes·next.js
Suroy1 天前
DockerView-Go:用 Go 写一个终端 Docker 监控工具,顺便做了个 Web 仪表盘
docker
云恒要逆袭2 天前
运行你的第一个Docker容器
后端·docker·容器
宋均浩2 天前
# Docker 镜像瘦身实战:从 1.2G 到 80MB 的五个优化步骤
ci/cd·docker
Avan_菜菜3 天前
FRP 内网穿透完整实战:从 HTTP 映射到 HTTPS 自签代理
运维·nginx·https
程序员老赵3 天前
10 分钟部署 OpenCode:Docker 一键安装,浏览器打开就能用 AI 写代码(附完整命令与排错)
docker·容器·ai编程
WangMingHua1113 天前
LM Studio Docker 部署——本地大模型一键启动
docker
曲幽4 天前
别再用网页翻译看源码了!你的私人翻译神器LibreTranslate,部署避坑指南来了
python·docker·web·pot·translate·libretranslate·arogstranslate
武子康6 天前
调查研究-183 Apple container:Mac 上用轻量 VM 跑 Linux 容器,Swift 会改写本地容器体验吗?
docker·容器·apple
ping某7 天前
为什么 Nginx 明明监听了 80,转发后端时却用了 4xxxx 端口?
后端·nginx