深色模式
Nginx 安装与反向代理
摘要:Nginx 最常见的角色是反向代理——对外只暴露 80/443,把请求按规则转发给后端真实服务。本文带你在 Linux 上装好 Nginx,写一个带 upstream 的反向代理配置,并验证热重载不中断连接。
适用环境
bash
cat /etc/os-release | grep -E '^(ID|VERSION_ID)='
sudo ss -ltnp | grep -E ':80 |:8080 ' # 确认 80 与后端端口未被占用
# 卸载系统自带的 httpd/apache 避免端口冲突(Debian 系用 apt remove)
sudo yum remove -y httpd 2>/dev/null || true1
2
3
4
5
2
3
4
5
操作步骤
1. 安装 Nginx
bash
# RHEL/Rocky/Alma:先装 epel 或用官方 nginx 仓库
sudo yum install -y nginx
# Debian/Ubuntu
sudo apt-get update && sudo apt-get install -y nginx1
2
3
4
5
2
3
4
5
2. 认识配置文件结构
bash
nginx -V 2>&1 | tr ' ' '\n' | grep -E 'conf-path|prefix' # 找到主配置路径
ls /etc/nginx/ # nginx.conf + conf.d/
ls /etc/nginx/conf.d/ # 站点配置放这里1
2
3
2
3
3. 定义 upstream(后端服务池)
nginx
# /etc/nginx/conf.d/app.conf
upstream backend {
server 127.0.0.1:8080 weight=1 max_fails=3 fail_timeout=10s;
server 127.0.0.1:8081 weight=1 max_fails=3 fail_timeout=10s;
keepalive 32; # 复用上游连接,减少 TIME_WAIT
}
server {
listen 80;
server_name _;
location / {
proxy_pass http://backend;
proxy_http_version 1.1; # keepalive 需要 1.1
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection ""; # 清掉 close,保持长连接
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
}
location = /healthz { # 给负载均衡/探活用的轻量接口
access_log off;
return 200 "ok\n";
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
4. 检查语法并热重载
bash
sudo nginx -t # 必须看到 syntax is ok / test is successful
sudo systemctl enable --now nginx
sudo systemctl reload nginx # 平滑加载新配置,不断连接1
2
3
2
3
DANGER
nginx -t 通过前不要执行 reload/restart。生产环境直接 restart 会短暂断开已建立的连接,应始终优先使用 nginx -t && systemctl reload nginx。
5. 起一个测试后端验证转发
bash
# 用 python 快速起两个"后端",返回不同标识
cd /tmp && python3 -m http.server 8080 >/dev/null 2>&1 &
cd /tmp && python3 -m http.server 8081 >/dev/null 2>&1 &1
2
3
2
3
验证
bash
# 1) 访问 80 端口,应被转发到后端
curl -i http://127.0.0.1/ | head -1 # HTTP/1.1 200 OK
# 2) 连续请求,确认两个后端都被调度到(默认轮询)
for i in $(seq 1 4); do curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1/; done
# 3) 探活接口
curl -s http://127.0.0.1/healthz # ok
# 4) 确认后端收到真实客户端 IP
sudo tail -n 5 /var/log/nginx/access.log1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
常见坑
WARNING
proxy_pass http://backend/; 末尾带 / 与不带 / 行为完全不同:带 / 会截断 location 匹配的前缀,不带则原样透传 URI。新手最常见的 404 就来自这里。
WARNING
忘记设置 proxy_http_version 1.1 和 proxy_set_header Connection "",keepalive 将完全不生效,上游 TIME_WAIT 连接会堆积。
DANGER
upstream 里填了监听在 127.0.0.1 的后端、但 Nginx 与后端不在同一台机器时,会全部 502。请先 curl http://<后端IP>:<端口> 确认后端可达再接入 upstream。