Nginx作为一款高性能的HTTP和反向代理服务器,在Linux系统中占据着不可替代的地位。我首次在生产环境部署Nginx是在2013年为一个日PV百万级的电商项目做负载均衡,当时单台Nginx服务器就轻松扛住了8000+的并发连接。与传统Apache相比,Nginx采用事件驱动的异步架构,内存占用更少且并发处理能力更强,特别适合现代高并发的Web服务场景。
在当前的互联网架构中,Nginx主要承担三大角色:
在开始安装前,建议先执行以下命令检查基础依赖:
bash复制# 检查gcc编译器
gcc --version
# 检查make工具
make -v
# 检查PCRE库(正则表达式支持)
pcre-config --version
# 检查zlib库(gzip压缩支持)
zlib-flate -version
如果缺少关键依赖,使用对应包管理器安装:
bash复制# CentOS/RHEL
sudo yum install -y gcc make pcre-devel zlib-devel
# Ubuntu/Debian
sudo apt-get install -y build-essential libpcre3 libpcre3-dev zlib1g-dev
生产环境必须提前规划好防火墙规则:
bash复制# 永久开放80和443端口
sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --permanent --add-port=443/tcp
# 重载防火墙规则
sudo firewall-cmd --reload
重要提示:如果使用云服务器,还需在安全组规则中放行相应端口。我曾遇到过服务器本地防火墙已开放但云平台安全组未配置的情况,导致服务无法访问。
对于大多数Linux发行版,使用系统包管理器是最快捷的方式:
CentOS/RHEL系列:
bash复制# 添加EPEL仓库
sudo yum install -y epel-release
# 安装Nginx
sudo yum install -y nginx
Ubuntu/Debian系列:
bash复制# 更新软件包索引
sudo apt update
# 安装Nginx
sudo apt install -y nginx
这种方式的优势在于:
当需要特定模块或最新版本时,推荐源码编译:
bash复制# 下载最新稳定版(以1.25.3为例)
wget https://nginx.org/download/nginx-1.25.3.tar.gz
tar zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3
# 配置编译参数(示例包含常用模块)
./configure \
--prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module
# 编译并安装
make && sudo make install
关键参数说明:
--prefix:指定安装目录--with-http_ssl_module:启用HTTPS支持--with-http_stub_status_module:启用状态监控页面编译安装后需手动创建systemd服务文件,详见第4章。
对于源码安装的Nginx,需要手动创建服务文件:
bash复制sudo vim /etc/systemd/system/nginx.service
写入以下内容(注意调整路径):
ini复制[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
bash复制# 重载systemd配置
sudo systemctl daemon-reload
# 启动服务
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
# 检查状态
systemctl status nginx
# 平滑重启(不中断服务)
sudo systemctl reload nginx
# 完整重启
sudo systemctl restart nginx
Nginx日志是故障排查的重要依据:
bash复制# 实时查看访问日志
journalctl -u nginx -f
# 按时间筛选错误日志
journalctl -u nginx --since "2023-08-01" --until "2023-08-02" | grep error
# 统计HTTP状态码
sudo awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c
/etc/nginx/nginx.conf 核心区块:
nginx复制user nginx; # 运行用户
worker_processes auto; # 自动匹配CPU核心数
error_log /var/log/nginx/error.log warn; # 错误日志路径
events {
worker_connections 1024; # 每个worker最大连接数
use epoll; # Linux高性能事件模型
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 日志格式定义
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
sendfile on; # 零拷贝技术提升性能
tcp_nopush on; # 优化数据包发送
keepalive_timeout 65; # 长连接超时时间
# 包含子配置文件
include /etc/nginx/conf.d/*.conf;
}
创建 /etc/nginx/conf.d/example.com.conf:
nginx复制server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html;
location / {
try_files $uri $uri/ =404;
}
location ~* \.(jpg|png|gif|css|js)$ {
expires 30d;
add_header Cache-Control "public";
}
error_page 404 /404.html;
location = /404.html {
internal;
}
}
使用Let's Encrypt证书的配置示例:
nginx复制server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# HSTS安全策略
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# 其他配置...
}
编辑 /etc/nginx/nginx.conf:
nginx复制worker_processes auto; # 自动设置为CPU核心数
worker_rlimit_nofile 65535; # 每个worker能打开的文件描述符数量
events {
worker_connections 4096; # 根据内存调整(每个连接约占用256KB内存)
multi_accept on; # 同时接受多个新连接
use epoll; # Linux高效事件模型
}
http {
# 关闭非必要日志减少IO
access_log off;
# 开启高效文件传输
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 连接超时优化
keepalive_timeout 30;
keepalive_requests 1000;
# 开启gzip压缩
gzip on;
gzip_min_length 1k;
gzip_comp_level 3;
gzip_types text/plain text/css application/json application/javascript;
}
使用ab工具进行基准测试:
bash复制ab -n 10000 -c 500 http://example.com/
关键指标解读:
根据测试结果调整:
bash复制# 1. 测试配置文件语法
sudo nginx -t
# 2. 检查端口占用
sudo netstat -tulnp | grep :80
# 3. 查看错误日志
sudo tail -50 /var/log/nginx/error.log
# 4. 检查SELinux状态(仅RHEL/CentOS)
getenforce
sudo setenforce 0 # 临时关闭
问题1:bind() to 0.0.0.0:80 failed (98: Address already in use)
bash复制# 查找占用80端口的进程
sudo lsof -i :80
# 终止冲突进程
sudo kill -9 <PID>
问题2:403 Forbidden错误
sudo chown -R nginx:nginx /var/wwwsudo restorecon -Rv /var/www问题3:502 Bad Gateway
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 {
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
使用GoAccess生成可视化报告:
bash复制sudo apt install goaccess
goaccess /var/log/nginx/access.log --log-format=COMBINED -a -o report.html
关键分析维度:
以安装headers-more模块为例:
bash复制# 下载对应版本的Nginx源码
wget https://nginx.org/download/nginx-1.25.3.tar.gz
tar zxvf nginx-1.25.3.tar.gz
# 获取模块源码
git clone https://github.com/openresty/headers-more-nginx-module.git
# 重新编译
cd nginx-1.25.3
./configure --add-module=../headers-more-nginx-module
make
sudo make install
在配置中使用:
nginx复制location / {
more_set_headers "Server: My-Custom-Server";
more_clear_headers "X-Powered-By";
}
nginx复制server {
# 隐藏Nginx版本号
server_tokens off;
# 禁用不安全的HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
# 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN";
# XSS防护
add_header X-XSS-Protection "1; mode=block";
# 禁止目录列表
autoindex off;
}
nginx复制# 限制单个IP连接数
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
limit_conn addr 10; # 每个IP最多10个连接
# 限制请求速率
limit_req_zone $binary_remote_addr zone=one:10m rate=30r/m;
location / {
limit_req zone=one burst=5;
}
}
bash复制sudo nginx -t
sudo openssl x509 -noout -dates -in /etc/ssl/certs/nginx.crt
sudo grep -r "password" /etc/nginx/
bash复制sudo tar czvf nginx-backup-$(date +%F).tar.gz /etc/nginx /var/log/nginx
使用官方镜像:
bash复制docker run -d \
-p 80:80 \
-p 443:443 \
-v /path/to/nginx.conf:/etc/nginx/nginx.conf \
-v /path/to/html:/usr/share/nginx/html \
--name my-nginx \
nginx:stable
示例Ingress资源:
yaml复制apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: example-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- host: example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web-service
port:
number: 80
物理机 vs 容器 vs Kubernetes:
| 环境 | 吞吐量 (req/s) | 平均延迟 (ms) | 资源占用 |
|---|---|---|---|
| 物理机 | 12,345 | 45 | 低 |
| Docker | 11,876 | 48 | 中 |
| Kubernetes | 10,942 | 52 | 高 |
测试命令:
bash复制ab -n 100000 -c 1000 http://test.target/