Docker部署Nginx和配置https

Docker部署Nginx和配置https

Nginx部署过程

# 防火墙开放需要使用的端口
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生成自签证书。

这里使用第三种方式。

# 生成私钥
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就大功搞成了。

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值