1. Nginx核心架构解析
Nginx作为一款高性能的Web服务器和反向代理服务器,其核心架构设计采用了事件驱动的异步非阻塞模型。与传统Apache的多进程/多线程模型不同,Nginx使用master-worker进程架构,master进程负责管理工作进程,而worker进程则使用单线程异步处理多个连接。
这种设计带来三个显著优势:
- 内存消耗极低 - 每个worker进程处理上千连接仅需2.5MB内存
- 高并发能力 - 实测单机可轻松支撑5万+并发连接
- 热部署支持 - 配置文件修改后可通过信号量通知worker平滑重启
注意:Nginx默认配置会创建与CPU核心数相同的worker进程,在/etc/nginx/nginx.conf中通过worker_processes参数设置。生产环境建议设置为auto以自动匹配CPU核心数。
2. 编译安装与性能调优
2.1 源码编译最佳实践
虽然各Linux发行版提供预编译包,但生产环境推荐源码编译以获得最佳性能。以下是关键编译参数示例:
bash复制./configure \
--prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-threads \
--with-file-aio \
--with-pcre-jit
关键模块说明:
- http_v2_module:支持HTTP/2协议
- pcre-jit:正则表达式JIT编译加速
- file-aio:异步文件IO提升静态文件性能
2.2 内核参数调优
在/etc/sysctl.conf中添加以下参数可突破默认连接数限制:
conf复制net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
fs.file-max = 999999
执行sysctl -p生效后,Nginx配置中需要同步调整:
nginx复制events {
worker_connections 65535;
multi_accept on;
use epoll;
}
3. 核心配置实战指南
3.1 虚拟主机配置模板
nginx复制server {
listen 80;
server_name example.com www.example.com;
# 强制HTTPS跳转
if ($scheme != "https") {
return 301 https://$host$request_uri;
}
root /var/www/example.com;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
add_header Cache-Control "public";
}
}
3.2 负载均衡配置示例
nginx复制upstream backend {
least_conn; # 最小连接数算法
server 192.168.1.101:8080 weight=3;
server 192.168.1.102:8080;
server 192.168.1.103:8080 backup; # 备用服务器
}
server {
listen 80;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
4. 安全加固方案
4.1 基础安全配置
nginx复制server {
# 禁用非必要HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
# 隐藏Nginx版本号
server_tokens off;
# 防止MIME类型混淆攻击
add_header X-Content-Type-Options "nosniff";
# 启用HSTS
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
}
4.2 限流防护配置
nginx复制# 定义限流区域
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
server {
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
proxy_pass http://api_backend;
}
}
5. 性能监控与日志分析
5.1 状态监控模块
启用stub_status模块后,通过http://server/nginx_status可获取关键指标:
code复制Active connections: 291
server accepts handled requests
16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106
指标说明:
- Waiting:保持空闲的连接数
- Reading:正在读取请求头的连接数
- Writing:正在处理响应的连接数
5.2 日志分析技巧
推荐日志格式配置:
nginx复制log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
使用GoAccess工具实时分析:
bash复制goaccess /var/log/nginx/access.log -o report.html --log-format=COMBINED
6. 常见问题排查手册
6.1 502 Bad Gateway问题
排查步骤:
- 检查后端服务是否存活:
curl -I http://backend - 查看Nginx错误日志:
tail -f /var/log/nginx/error.log - 确认proxy_pass地址正确性
- 检查防火墙设置:
iptables -L -n - 测试FastCGI连接:
cgi-fcgi -bind -connect /run/php-fpm.sock
6.2 性能突然下降
检查清单:
- 系统负载:
uptime、top - 网络状况:
iftop -nNP - 磁盘IO:
iostat -x 1 - 连接状态:
ss -s - 查看当前请求数:
netstat -an | grep :80 | wc -l
7. 高级功能实现
7.1 动态模块加载
Nginx 1.9.11+支持动态模块,以http_image_filter_module为例:
bash复制# 编译动态模块
./configure --add-dynamic-module=modules/http_image_filter_module
make modules
# 加载配置
load_module modules/ngx_http_image_filter_module.so;
7.2 Lua脚本扩展
通过OpenResty实现复杂业务逻辑:
nginx复制location /api {
access_by_lua_block {
local token = ngx.var.arg_token
if not token then
ngx.exit(ngx.HTTP_FORBIDDEN)
end
}
content_by_lua_file /path/to/handler.lua;
}
8. 容器化部署方案
8.1 Docker最佳实践
推荐使用官方镜像并自定义配置:
dockerfile复制FROM nginx:1.23-alpine
RUN rm /etc/nginx/conf.d/*
COPY nginx.conf /etc/nginx/
COPY sites/ /etc/nginx/conf.d/
VOLUME ["/var/log/nginx"]
EXPOSE 80 443
CMD ["nginx", "-g", "daemon off;"]
启动命令:
bash复制docker run -d \
-p 80:80 \
-p 443:443 \
-v ./logs:/var/log/nginx \
--name nginx \
custom-nginx
8.2 Kubernetes Ingress配置
示例Ingress资源定义:
yaml复制apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
ingressClassName: nginx
rules:
- host: example.com
http:
paths:
- path: /api/(.*)
pathType: Prefix
backend:
service:
name: api-service
port:
number: 8080