云服务器配置指南 (六):Nginx,流量的指挥官

如果把服务器比作一家公司,那 Nginx 就是前台接待。

所有从外面进来的请求(客户),都得先经过 Nginx。它负责把请求分发给后端的 Python、Node.js 服务(各部门员工)。

为什么不让客户直接找员工?因为不安全,也不专业。Nginx 能帮我们处理 HTTPS 加密、负载均衡、静态资源缓存,让后端专心写业务逻辑。

本章我们将用 Docker 部署 Nginx,并配置反向代理和 HTTPS。


6.1 为什么要用 Docker 部署 Nginx?

直接 apt install nginx 不行吗?行,但不好。

  • 环境污染:配置文件散落在 /etc/nginx/var/log/nginx 各处,备份迁移麻烦。
  • 版本管理:想升级或降级版本,Docker 只需要改个 tag,系统安装得折腾半天。

用 Docker,我们可以把所有配置、证书、日志都挂载到一个目录下,打包带走就是全套服务。


6.2 动手部署

1. 规划目录

好的目录结构是成功的一半。

1
2
mkdir -p ~/nginx/{conf.d,certs,logs,html}
cd ~/nginx

2. 编写 docker-compose.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
services:
nginx:
image: nginx:alpine
container_name: nginx
restart: always
ports:
- "80:80"
- "443:443"
volumes:
- ./conf.d:/etc/nginx/conf.d
- ./certs:/etc/nginx/certs
- ./logs:/var/log/nginx
- ./html:/usr/share/nginx/html
# 这一步很重要,让 Nginx 能访问到宿主机上的其他容器
extra_hosts:
- "host.docker.internal:host-gateway"

3. 编写默认配置

conf.d 下新建 default.conf

1
2
3
4
5
6
7
8
9
server {
listen 80;
server_name localhost;

location / {
root /usr/share/nginx/html;
index index.html;
}
}

随便写个 html/index.html,然后启动:

1
docker compose up -d

访问你的 IP,应该能看到页面了。


6.3 反向代理:让 Nginx 干活

假设你在 3000 端口跑了个 Node.js 服务,怎么让用户通过域名访问,而不是 IP:3000?

修改 conf.d/default.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
server {
listen 80;
server_name yourdomain.com;

location / {
# 这里的 host.docker.internal 指向宿主机
proxy_pass http://host.docker.internal:3000;

# 别忘了带上这些头,不然后端拿不到真实 IP
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

重启 Nginx:

1
docker compose restart

现在访问域名,Nginx 就会自动把请求转发给 3000 端口的服务了。


6.4 HTTPS:给网站上把锁

没有 HTTPS 的网站,Chrome 会提示“不安全”,用户看了都想跑。
我们可以用 acme.sh 免费申请 Let’s Encrypt 证书。

1. 申请证书

推荐使用 acme.sh 的 Docker 模式,或者直接在宿主机安装。这里演示宿主机安装:

1
2
curl https://get.acme.sh | sh
source ~/.bashrc

如果你有阿里云/腾讯云的 API Key,可以用 DNS 方式自动验证(推荐):

1
2
3
export Ali_Key="你的Key"
export Ali_Secret="你的Secret"
acme.sh --issue --dns dns_ali -d yourdomain.com

2. 安装证书

把证书安装到我们映射的目录:

1
2
3
4
acme.sh --install-cert -d yourdomain.com \
--key-file ~/nginx/certs/key.pem \
--fullchain-file ~/nginx/certs/cert.pem \
--reloadcmd "docker compose restart nginx"

3. 配置 Nginx 开启 HTTPS

修改 conf.d/default.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 强制跳转 HTTPS
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}

server {
listen 443 ssl;
server_name yourdomain.com;

ssl_certificate /etc/nginx/certs/cert.pem;
ssl_certificate_key /etc/nginx/certs/key.pem;

location / {
proxy_pass http://host.docker.internal:3000;
# ... 其他 proxy_set_header
}
}

重启 Nginx,你的网站就有小绿锁了!


总结

Nginx 是服务器的大门,反向代理和 HTTPS 是它的两把门神。
配置虽然有点繁琐,但一旦配好,你的服务就拥有了企业级的入口能力。

下一章,我们将部署一些实用的服务,比如 Portainer(图形化管理 Docker)和 Uptime Kuma(监控服务状态)。