在 Debian 上搭建的 LNMP(Linux + Nginx + MySQL/MariaDB + PHP) 环境,性能优化通常从 系统层、Nginx、PHP、MySQL、缓存、监控 六个方面入手。下面给你一套实用、可落地的优化方案(适合生产环境)。
编辑 /etc/sysctl.conf:
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
vm.swappiness = 10
应用:
sysctl -p
ulimit -n 65535
编辑 /etc/security/limits.conf:
* soft nofile 65535
* hard nofile 65535
worker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 10240;
use epoll;
multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 30;
gzip on;
gzip_min_length 1k;
gzip_comp_level 5;
gzip_types text/css application/javascript image/svg+xml;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 30d;
access_log off;
}
编辑:
/etc/php/*/fpm/pool.d/www.conf
pm = dynamic
pm.max_children = 120
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 40
pm.max_requests = 1000
内存估算:
max_children × 单个PHP进程内存(一般 30~80MB)
expose_php = Off
disable_functions = exec,passthru,shell_exec,system
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
opcache.validate_timestamps=0
示例(2G~4G 内存服务器):
[mysqld]
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
max_connections = 300
query_cache_type = 0
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
SHOW PROCESSLIST;
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=PHP:100m;
Debian 安装:
apt install redis-server
htopiotopnetdataPrometheus + Grafanaab -n 10000 -c 200 http://domain.com/
或:
wrk -t4 -c200 -d30s http://domain.com/
| 问题 | 原因 | 解决 |
|---|---|---|
| CPU 高 | PHP 逻辑重 | OPcache + 代码优化 |
| 内存爆 | FPM 过多 | 降低 max_children |
| 磁盘 IO 高 | 日志 / 数据库 | SSD + 缓存 |
| 连接数不够 | 系统限制 | ulimit + sysctl |
如果你愿意,可以告诉我:
我可以直接给你一份可复制的配置文件。