nginx安装配置、故障处置、性能优化

第一部分:安装与配置

一、安装 Nginx

在 CentOS/RHEL/Rocky Linux 上安装

复制代码
# 1. 添加 EPEL 仓库(如果需要)
sudo yum install epel-release

# 2. 安装 Nginx
sudo yum install nginx

# 3. 启动并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx

# 4. 检查状态
sudo systemctl status nginx

在 Ubuntu/Debian 上安装

复制代码
# 1. 更新软件包列表
sudo apt update

# 2. 安装 Nginx
sudo apt install nginx

# 3. 启动并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx

# 4. 检查状态
sudo systemctl status nginx

从源码编译安装(用于特定需求)

复制代码
# 下载源码
wget http://nginx.org/download/nginx-1.24.0.tar.gz
tar -zxvf nginx-1.24.0.tar.gz
cd nginx-1.24.0

# 配置编译选项
./configure \
  --prefix=/usr/local/nginx \
  --with-http_ssl_module \
  --with-http_v2_module \
  --with-http_gzip_static_module \
  --with-http_stub_status_module \
  --with-threads

# 编译和安装
make && sudo make install

二、核心配置文件结构

复制代码
/etc/nginx/
├── nginx.conf          # 主配置文件
├── conf.d/             # 额外的配置文件目录
│   └── default.conf    # 默认服务器配置
├── sites-available/    # 可用的虚拟主机配置(Ubuntu)
├── sites-enabled/      # 已启用的虚拟主机配置(Ubuntu)
└── modules-available/  # 模块配置

三、基础配置示例

1. 静态网站配置

/etc/nginx/conf.d/static-site.conf

复制代码
server {
    listen 80;
    server_name example.com www.example.com;
    
    # 网站根目录
    root /var/www/html;
    index index.html index.htm;
    
    # 开启 Gzip 压缩
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    
    # 安全头
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    
    # 静态资源缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
    
    # 错误页面
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
}

2. 反向代理配置(代理到后端应用)

/etc/nginx/conf.d/reverse-proxy.conf

复制代码
upstream backend {
    # 负载均衡策略
    least_conn;  # 最少连接数
    
    # 后端服务器列表
    server 192.168.1.101:8080 weight=3;
    server 192.168.1.102:8080 weight=2;
    server 192.168.1.103:8080 weight=1 backup;  # 备份服务器
}

server {
    listen 80;
    server_name api.example.com;
    
    # 客户端超时设置
    client_max_body_size 10m;
    client_body_timeout 60;
    client_header_timeout 60;
    
    # 代理设置
    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        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_connect_timeout 30s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # 缓冲设置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        
        # 禁用代理缓冲用于实时应用
        # proxy_buffering off;
    }
    
    # 健康检查端点
    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        allow 192.168.1.0/24;
        deny all;
    }
}

3. SSL/TLS 配置

复制代码
server {
    listen 443 ssl http2;
    server_name example.com;
    
    # SSL 证书路径
    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    
    # SSL 协议配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    # HSTS 头
    add_header Strict-Transport-Security "max-age=63072000" always;
    
    # 其他配置...
}

# HTTP 重定向到 HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

四、配置管理命令

复制代码
# 测试配置文件语法
sudo nginx -t

# 重新加载配置(不中断服务)
sudo nginx -s reload

# 重新打开日志文件
sudo nginx -s reopen

# 优雅停止
sudo nginx -s quit

# 快速停止
sudo nginx -s stop

第二部分:故障处置

一、常用诊断命令

复制代码
# 检查 Nginx 进程状态
ps aux | grep nginx
systemctl status nginx

# 检查端口监听
netstat -tulpn | grep :80
ss -tulpn | grep :80

# 检查配置文件语法
nginx -t

# 查看错误日志
tail -f /var/log/nginx/error.log
tail -f /var/log/nginx/access.log

# 实时查看访问日志(显示客户端IP)
tail -f /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -nr

二、常见故障及解决方案

1. 502 Bad Gateway

原因:Nginx 无法连接到上游服务器。

排查步骤

复制代码
# 检查后端服务是否运行
curl -I http://backend-server:port

# 检查防火墙规则
iptables -L -n
firewall-cmd --list-all

# 检查 Nginx 错误日志
grep "502" /var/log/nginx/error.log

# 测试网络连通性
telnet backend-server port
ping backend-server

解决方案

  • 确保后端服务正在运行

  • 检查防火墙设置

  • 增加代理超时时间:

    proxy_connect_timeout 60s;
    proxy_read_timeout 60s;

2. 413 Request Entity Too Large

解决方案

复制代码
# 在 http, server 或 location 块中增加
client_max_body_size 100M;

3. 504 Gateway Timeout

解决方案

复制代码
# 增加超时时间
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;

# 或者在后端应用优化响应时间

4. 权限问题

复制代码
# 检查文件和目录权限
ls -la /var/www/html/

# 确保 Nginx 用户有读取权限
sudo chown -R nginx:nginx /var/www/html/
sudo chmod -R 755 /var/www/html/

5. 地址已被占用

复制代码
# 查找占用端口的进程
sudo lsof -i :80
sudo netstat -tulpn | grep :80

# 杀死占用进程或更改 Nginx 监听端口

三、日志分析技巧

复制代码
# 查看最近错误
tail -100 /var/log/nginx/error.log

# 统计 HTTP 状态码
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn

# 查找最频繁的访问 IP
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

# 查看响应时间过长的请求
awk '($NF > 1) {print $7, $NF}' /var/log/nginx/access.log | sort -k2 -rn | head -20

第三部分:性能优化

一、操作系统层面优化

1. 调整文件描述符限制

复制代码
# 临时设置
ulimit -n 65536

# 永久设置 - 编辑 /etc/security/limits.conf
echo "nginx soft nofile 65536" >> /etc/security/limits.conf
echo "nginx hard nofile 65536" >> /etc/security/limits.conf

# 在 systemd 服务中设置
# 编辑 /etc/systemd/system/nginx.service.d/override.conf
[Service]
LimitNOFILE=65536

2. 网络栈优化

/etc/sysctl.conf

复制代码
# 增加端口范围
net.ipv4.ip_local_port_range = 1024 65535

# 增加最大连接数
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65536

# TCP 优化
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_max_syn_backlog = 65536
net.ipv4.tcp_syncookies = 1

# 内存设置
net.ipv4.tcp_rmem = 4096 87380 67108864
net.ipv4.tcp_wmem = 4096 65536 67108864
net.core.rmem_max = 67108864
net.core.wmem_max = 67108864

应用配置:sudo sysctl -p

二、Nginx 配置优化

1. 工作进程优化

/etc/nginx/nginx.conf

复制代码
# 工作进程数,通常设置为 CPU 核心数
worker_processes auto;

# 每个工作进程的最大连接数
events {
    worker_connections 65536;
    use epoll;  # 在 Linux 上使用 epoll 事件模型
    multi_accept on;  # 一个工作进程同时接受多个新连接
}

# 工作进程绑定到特定 CPU(可选)
worker_cpu_affinity auto;

2. HTTP 基础优化

复制代码
http {
    # 基础性能设置
    sendfile on;           # 使用 sendfile 系统调用
    tcp_nopush on;         # 在 sendfile 开启时生效,优化数据包发送
    tcp_nodelay on;        # 禁用 Nagle 算法,提高实时性
    keepalive_timeout 65;  # 保持连接超时时间
    types_hash_max_size 2048;
    
    # 缓冲设置
    client_body_buffer_size 128k;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 4k;
    client_max_body_size 100m;
    
    # 超时设置
    client_body_timeout 12;
    client_header_timeout 12;
    send_timeout 10;
    
    # 文件缓存
    open_file_cache max=200000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;
    
    # Gzip 压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/json
        application/javascript
        application/xml+rss
        application/atom+xml
        image/svg+xml;
    
    # 静态文件缓存
    server {
        location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf|txt)$ {
            expires 365d;
            add_header Cache-Control "public, immutable";
            access_log off;
        }
    }
}

3. 反向代理优化

复制代码
upstream backend {
    server backend1.example.com weight=5;
    server backend2.example.com;
    server backend3.example.com backup;
    
    # 保持连接池
    keepalive 32;
}

server {
    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        
        # 缓冲优化
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        proxy_busy_buffers_size 16k;
        
        # 超时优化
        proxy_connect_timeout 30s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # 启用响应缓存
        proxy_cache my_cache;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
    }
}

4. 缓存配置

复制代码
# 在 http 块中定义缓存路径
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m 
                 max_size=10g inactive=60m use_temp_path=off;

server {
    location / {
        proxy_cache my_cache;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
        add_header X-Cache-Status $upstream_cache_status;
    }
}

三、监控与性能测试

1. 启用状态监控

复制代码
server {
    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        allow 192.168.1.0/24;
        deny all;
    }
}

访问 http://yourserver/nginx_status 可以看到:

复制代码
Active connections: 291
server accepts handled requests
 16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106

2. 性能测试工具

复制代码
# 使用 ab (Apache Bench) 进行压力测试
ab -n 1000 -c 100 http://yourserver/

# 使用 wrk 进行更高级的测试
wrk -t12 -c400 -d30s http://yourserver/

# 使用 siege
siege -c 100 -t 1M http://yourserver/

四、安全优化

复制代码
# 隐藏 Nginx 版本号
server_tokens off;

# 安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

# 限制请求方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
    return 405;
}

# 速率限制
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

location /login {
    limit_req zone=one burst=5 nodelay;
}

总结

性能优化检查清单

  1. ✅ 调整工作进程数和连接数

  2. ✅ 启用 sendfile、tcp_nopush、tcp_nodelay

  3. ✅ 配置合理的缓冲区大小

  4. ✅ 启用 Gzip 压缩

  5. ✅ 设置静态资源缓存

  6. ✅ 优化反向代理配置

  7. ✅ 配置操作系统参数

  8. ✅ 实施安全加固措施

  9. ✅ 设置监控和日志分析

  10. ✅ 定期进行压力测试

通过系统化的配置、监控和优化,Nginx 可以轻松应对高并发场景,提供稳定高效的服务。

相关推荐
未来之窗软件服务2 小时前
服务器运维(十一)SQLite3 php封装——东方仙盟炼气期
运维·服务器·sqlite·服务器运维·数据库驱动·东方仙盟
yachuan_qiao3 小时前
专业的建筑设备监控管理系统选哪家
大数据·运维·python
cccccc语言我来了4 小时前
深入理解 Linux(7) 命令与动态库:从文件操作到程序链接的实践指南
android·linux·运维
Lynnxiaowen4 小时前
今天我们开始学习Linux自动化运维Ansible基础
linux·运维·学习·自动化·云计算·ansible
NiKo_W4 小时前
Linux 传输层协议
linux·运维·网络·tcp协议·传输层·udp协议
夜月yeyue4 小时前
Linux 中断处理机制详解:上下半部、内核线程与中断线程化
linux·运维·单片机·嵌入式硬件·uboot·bootloard
机器人行业研究员4 小时前
防爆六维力传感器的本质安全,破解高危环境自动化难题
运维·自动化
云计算老刘5 小时前
1. Cockpit 管理服务器;2. Linux 软件包管理
linux·运维·服务器·云原生·云计算
海域云SeaArea_5 小时前
ubuntu22.01安装NVIDIA-Docker
运维·docker·容器