温馨提示×

如何优化Debian的nginx性能

小樊
38
2026-09-12 11:02:38
栏目: 智能运维

在 Debian 上优化 Nginx 性能,可以从系统层面、Nginx 配置、缓存、网络和安全几个方向入手。下面是一套比较实用、可落地的优化方案。


一、系统层面优化(Debian)

1. 调整内核参数(TCP / 文件句柄)

编辑 /etc/sysctl.conf 或 /etc/sysctl.d/99-nginx.conf:

# 文件描述符
fs.file-max = 1000000

# TCP 队列
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535

# TCP 连接复用
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 15

# 内存相关
net.ipv4.tcp_rmem = 4096 87380 67108864
net.ipv4.tcp_wmem = 4096 65536 67108864

应用:

sysctl -p

2. 提高用户文件句柄限制

/etc/security/limits.conf:

* soft nofile 1000000
* hard nofile 1000000

二、Nginx 核心配置优化

配置文件通常在:

/etc/nginx/nginx.conf

1. Worker 进程与连接数

worker_processes auto;
worker_rlimit_nofile 100000;

events {
    worker_connections 10240;
    use epoll;
    multi_accept on;
}

2. 开启高效传输

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 30;
    keepalive_requests 100;
}

3. 开启 Gzip(减少传输体积)

gzip on;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

三、缓存与静态资源优化

1. 静态资源缓存

location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2)$ {
    expires 30d;
    access_log off;
}

2. 开启 open_file_cache

open_file_cache max=100000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
open_file_cache_errors on;

四、PHP / 反向代理场景优化

1. PHP-FPM(如 WordPress)

location ~ \.php$ {
    fastcgi_pass unix:/run/php/php8.2-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;

    fastcgi_buffers 16 16k;
    fastcgi_buffer_size 32k;
    fastcgi_read_timeout 60s;
}

2. 反向代理优化

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mycache:10m max_size=1g inactive=60m;
proxy_cache mycache;

location / {
    proxy_pass http://backend;
    proxy_set_header Host $host;
    proxy_cache_use_stale error timeout updating;
}

五、SSL / HTTPS 优化

1. 启用 HTTP/2

listen 443 ssl http2;

2. SSL 会话复用

ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets on;

3. 使用现代加密套件

ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;

六、日志与监控

1. 减少日志压力

access_log off; # 静态资源
# 或
access_log /var/log/nginx/access.log main buffer=32k flush=5s;

2. 监控工具

  • nginx -T(检查配置)
  • htop, vmstat
  • goaccess(日志分析)
  • prometheus + nginx-exporter

七、Debian 专项建议

  • 使用 Debian 12 + Nginx 官方源
  • 避免使用 apt 旧版本:
apt install nginx-full
  • 开启 systemd 限制:
[Service]
LimitNOFILE=100000

八、快速检查清单 ✅

  • [ ] worker_processes = auto
  • [ ] sendfile = on
  • [ ] gzip = on
  • [ ] keepalive = on
  • [ ] 静态资源缓存
  • [ ] HTTP/2
  • [ ] 文件句柄提升
  • [ ] sysctl 调优

如果你能告诉我:

  • Debian 版本
  • Nginx 用途(静态 / PHP / 反向代理)
  • 并发量级别

我可以给你一套更精准的配置文件。

0 踩