当前位置: 首页 > news >正文

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_typestext/plaintext/csstext/xmltext/javascriptapplication/jsonapplication/javascriptapplication/xml+rssapplication/atom+xmlimage/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 requests16630948 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 可以轻松应对高并发场景,提供稳定高效的服务。

http://www.dtcms.com/a/601364.html

相关文章:

  • 网上商城互联网网站开发网站建设流程效果
  • 商品案例-组件封装(vue)
  • 新视角看 js 的数据类型
  • PySide6 + QML - QSerialPort01 - 扫描操作系统上有效的串口
  • 【前端面试】HTML篇
  • Next.js第四章(路由导航)
  • 从jsp打开一个html,怎么把jsp的某些参数传递给html
  • 谷歌google官方网站网站开发 书籍
  • 北京网站备案公司安徽观元建设有限公司网站
  • 若依plus请求加解密
  • PHP Filter:深入了解其功能与实现
  • Linux基础指令(简易版)
  • 农田灌区监测设备:赋能现代农业的精准感知与智能调控
  • 中山 灯饰 骏域网站建设专家百度关键词推广帝搜软件
  • 自己怎么做 优惠券网站西京一师一优课建设网站
  • CST电动车EMC仿真(二)——电机控制器MCU的EMC仿真
  • WPP Media(群邑)DOOH 解决方案 重构数字户外广告价值
  • 基于SpringBoot+Vue的美容美发在线预约系统的设计与实现【附源码】
  • 数字化转型改变了什么?从技术底层到业务本质的深度重构
  • 从 “被动抢修” 到 “主动防控”,安科瑞 mini 智能微断,重构末端配电安全新逻辑
  • 从经验到算法:智能获客系统如何重构ToB销售效率
  • Oracle 19C 数据字典 DBA_HIST_SEG_STAT 详细说明
  • tsfile.raw提示
  • JAVA中六种策略模式的实现
  • 【ZeroRange WebRTC】TLS 底层原理与工作机制(深入解析)
  • 【论文阅读16】-LLM-TSFD:一种基于大型语言模型的工业时间序列人机回路故障诊断方法
  • 联想键盘失灵处理方法
  • 网站建设scyiyouhtml5模板之家
  • 做网站网络公司泉州住房建设局网站
  • 电子绕核运动为何不辐射能量、不坠入原子核?