优化 Debian + LNMP(Linux + Nginx + MySQL/MariaDB + PHP) 可以从 系统、Nginx、PHP、MySQL、安全、缓存 多个层面来做。下面给你一套可落地的优化方案,从基础到进阶,适合生产环境。
apt update && apt upgrade -y
apt autoremove -y
关闭不必要服务:
systemctl disable bluetooth
systemctl disable cups
编辑:
vim /etc/security/limits.conf
添加:
* soft nofile 65535
* hard nofile 65535
vim /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
worker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 10240;
use epoll;
}
gzip on;
gzip_comp_level 5;
gzip_min_length 1k;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
(Brotli 性能更好,但需编译)
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2)$ {
expires 30d;
access_log off;
}
access_log off;
编辑:
vim /etc/php/*/fpm/pool.d/www.conf
推荐配置(依内存调整):
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
示例内存计算:
每个 PHP 进程 30–50MB
2G 内存服务器:max_children ≈ 40
php -m
卸载未使用模块:
apt remove php8.x-xml php8.x-sqlite3
memory_limit = 256M
max_execution_time = 60
upload_max_filesize = 50M
post_max_size = 50M
[mysqld]
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
max_connections = 200
query_cache_type = 0
table_open_cache = 4000
innodb_buffer_pool_size ≈ 内存的 50%–70%
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost','127.0.0.1');
FLUSH PRIVILEGES;
apt install redis-server php-redis
PHP 使用 Redis 缓存:
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.validate_timestamps=0
chown -R www-data:www-data /var/www
apt install ufw
ufw allow 22,80,443/tcp
ufw enable
apt install certbot python3-certbot-nginx
certbot --nginx
| 项目 | 建议 |
|---|---|
| Web | Nginx |
| PHP | PHP-FPM |
| DB | MariaDB |
| 缓存 | Redis + OPCache |
| 部署 | Git / CI |
| 监控 | htop / netdata |
htop
iotop
ss -antp
vmstat 1
压力测试:
apt install apache2-utils
ab -n 5000 -c 100 http://example.com/
你可以直接告诉我:
我可以 直接给你一套定制 LNMP 优化配置文件 ✅