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就大功搞成了。

相关推荐
j***29481 天前
Redis 设置密码(配置文件、docker容器、命令行3种场景)
数据库·redis·docker
小兔薯了1 天前
7. LNMP-wordpress
android·运维·服务器·数据库·nginx·php
8***84821 天前
macOs安装docker且在docker上部署nginx+php
nginx·macos·docker
p***92481 天前
服务器部署,用 nginx 部署后页面刷新 404 问题,宝塔面板修改(修改 nginx.conf 配置文件)
运维·服务器·nginx
星环处相逢1 天前
Nginx 优化与防盗链及扩展配置指南
服务器·前端·nginx
w***37511 天前
Nginx 的 proxy_pass 使用简介
运维·nginx
A***F1571 天前
从零到上线:Node.js 项目的完整部署流程(包含 Docker 和 CICD)
docker·容器·node.js
车前端1 天前
现代 Nginx 优化实践:架构、配置与性能调优
前端·nginx
i***51261 天前
springboot整合libreoffice(两种方式,使用本地和远程的libreoffice);docker中同时部署应用和libreoffice
spring boot·后端·docker
Brown.alexis1 天前
docker安装redis7
运维·docker·容器