docker 中的 nginx 配置域名及https
背景
最近项目要上线,要给原来 ip 地址 + 端口访问的项目绑定域名,但两个前端项目都是用多阶段构建后将 dist 静态文件放到 nginx 镜像中。所以要配置的 nginx 也在 docker 容器中。所以写此文章记录部署过程。
一共有两个项目:官网和 cms 管理平台,这两个项目要部署在一台云服务器上,同时两个项目对应不同的域名。因为两个前端项目都是用 nginx 容器启动的,改前端项目的 dockerfile 和 nginx配置都会很麻烦。所以单独启动一个 nginx 容器用于反向代理,以实现在一台主机绑定不同的子域名,并配置 https。
流程
1. 添加域名
首先找运维申请绑定域名和 https 的文件。
- xxxx.crt: 域名的证书
- xxxx.key: 升级 https时使用
- xxxx.pem: 升级 https时使用
以 Ubuntu 20.04 系统为例,将 xxxx.crt 上传到 /usr/local/share/ca-certificates
目录下。
然后更新证书
sudo update-ca-certificates
2. 配置 nginx ssl
将 xxxx.key 和 xxxx.pem 上传到 nginx /etc/ssl
目录下
3. 更改 nginx 配置文件
这里我是将官网前端部署到了宿主机的 81 端口,cms 管理平台部署到 82 端口。
所以这里使用反向代理将 http 和 https 的访问代理到对应的服务上。
按需更改下面的 nginx.conf 文件,其中有注释的地方是需要更改或注意的。
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
# HTTP server
server {
listen 80;
# 要添加的域名 A
server_name A;
location / {
# 服务的实际地址
proxy_pass http://ip:port;
}
location @router {
rewrite ^.*$ /index.html last;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
# HTTP server
server {
listen 80;
# 要添加的域名 B
server_name B;
location / {
# 服务的实际地址
proxy_pass http://ip:port;
}
location @router {
rewrite ^.*$ /index.html last;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
# HTTPS server
server {
listen 443 ssl;
# 要添加的域名 A
server_name A;
# 这里填写 nginx 容器中的 ssl 文件地址
ssl_certificate /etc/ssl/Axxxx.pem;
ssl_certificate_key /etc/ssl/Axxxx.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_prefer_server_ciphers on;
location / {
# 服务的实际地址
proxy_pass http://ip:port;
}
location @router {
rewrite ^.*$ /index.html last;
}
# 当前端访问后端接口时,会携带着 api 字段,将请求反向代理到指定的后端服务
location /api {
proxy_pass http://ip:port/api;
}
}
# HTTPS server
server {
listen 443 ssl;
# 要添加的域名 B
server_name B;
# 这里填写 nginx 容器中的 ssl 文件地址
ssl_certificate /etc/ssl/Bxxxx.pem;
ssl_certificate_key /etc/ssl/Bxxxx.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_prefer_server_ciphers on;
location / {
# 服务的实际地址
proxy_pass http://ip:port;
}
location @router {
rewrite ^.*$ /index.html last;
}
# 当前端访问后端接口时,会携带着 api 字段,将请求反向代理到指定的后端服务
location /api {
proxy_pass http://ip:port/api;
}
}
}
注意!
- 如果 nginx 容器直接就存在,请注意是否暴露了 443 端口。
- 进入到 nginx 容器修改完 nginx 内部的 nginx.conf 文件后,需要执行
nginx -s reload
,重新加载配置文件。