7.8.1 典型Web应用架构与Nginx角色
典型 Web 应用架构由接入层、应用层、缓存层、数据库层与可观测性体系组成。Nginx处于接入层或边缘层,承担统一入口、反向代理、负载均衡、TLS终止、静态资源分发与安全策略实施等职责,是流量治理与故障隔离的关键组件。
在三层架构中,Nginx作为反向代理与负载均衡器位于公网入口与应用服务器之间,处理TLS终止、连接复用、限流与请求路由。如下示例实现两个后端节点的负载均衡与健康切换:
# /etc/nginx/conf.d/app.conf
upstream app_backend {
server 10.0.0.11:8080 weight=2 max_fails=3 fail_timeout=10s;
server 10.0.0.12:8080 weight=1 max_fails=3 fail_timeout=10s;
keepalive 64;
}
server {
listen 80;
server_name www.example.com;
location / {
proxy_pass http://app_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
预期效果:访问 www.example.com 时请求被分发至两个后端,后端故障时自动摘除。
在动静分离架构中,Nginx直接提供静态资源并对后端应用减压。以下配置将 /static/ 走本地目录,其余走后端:
# /etc/nginx/conf.d/static.conf
server {
listen 80;
server_name static.example.com;
location /static/ {
alias /data/www/static/;
access_log /var/log/nginx/static_access.log;
expires 30d;
}
location / {
proxy_pass http://app_backend;
}
}
在微服务/API前置场景中,Nginx可充当轻量级网关,实现基于路径的路由与限流:
# /etc/nginx/conf.d/gateway.conf
limit_req_zone $binary_remote_addr zone=perip:10m rate=5r/s;
server {
listen 80;
server_name api.example.com;
location /user/ {
limit_req zone=perip burst=10 nodelay;
proxy_pass http://user_svc;
}
location /order/ {
proxy_pass http://order_svc;
}
}
高可用架构中常与Keepalived配合形成VIP漂移。Nginx主备均部署,VIP漂移后流量无感切换。
# 安装与启动(以 Ubuntu 为例)
sudo apt-get update
sudo apt-get install -y nginx
sudo systemctl enable --now nginx
# 检查配置并重载
sudo nginx -t
sudo systemctl reload nginx
可观测性方面,建议开启状态接口与结构化日志,便于接入Prometheus或ELK:
# /etc/nginx/conf.d/status.conf
server {
listen 8080;
server_name 127.0.0.1;
location /nginx_status {
stub_status;
allow 127.0.0.1;
deny all;
}
}
常见排错流程与命令示例:
# 1. 配置语法检查
sudo nginx -t
# 2. 查看错误日志
sudo tail -n 50 /var/log/nginx/error.log
# 3. 检查端口监听
sudo ss -lntp | grep nginx
# 4. 验证后端连通性
curl -I http://10.0.0.11:8080/health
curl -I http://10.0.0.12:8080/health
# 5. 验证Nginx入口
curl -I http://www.example.com/
常见错误与解决思路:
- 502 Bad Gateway:后端不可达或超时;检查后端服务状态与防火墙,确认 proxy_read_timeout。
- 404 静态资源:alias 路径错误或权限不足;检查目录权限与路径是否匹配。
- 配置变更无效:未重载或语法错误;nginx -t 后 systemctl reload nginx。
练习(可在本地或测试机完成):
1. 搭建两个后端(如 python -m http.server 8080),配置Nginx负载均衡并验证权重效果。
2. 配置动静分离,将 /static/ 指向本地目录并加 expires,验证浏览器缓存头。
3. 添加限流规则,对 /api/ 进行 5r/s 限制,观察 429 返回码。
4. 开启 stub_status,用 curl http://127.0.0.1:8080/nginx_status 查看指标。
通过以上示例可清晰理解Nginx在典型Web应用架构中的入口、分发、优化与治理角色,并掌握基础部署与排错方法。