在 Debian 上优化 LNMP(Linux + Nginx + MySQL/MariaDB + PHP) 配置,通常从 系统层、Nginx、PHP、MySQL/MariaDB、缓存与安全 五个方面入手。下面给你一套生产环境常用优化方案,按模块说明,适合中小到中大型网站。
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
systemctl disable bluetooth
systemctl disable cups
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;
events {
worker_connections 10240;
use epoll;
multi_accept on;
}
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
gzip on;
gzip_comp_level 5;
gzip_min_length 1k;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss;
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2)$ {
expires 30d;
access_log off;
}
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
limit_req zone=one burst=20 nodelay;
vim /etc/php/8.x/fpm/pool.d/www.conf
推荐配置(4 核 8G 示例):
pm = dynamic
pm.max_children = 80
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30
pm.max_requests = 500
如果是 高并发 API:
pm = static
pm.max_children = 100
vim /etc/php/8.x/fpm/php.ini
memory_limit = 256M
upload_max_filesize = 50M
post_max_size = 50M
max_execution_time = 60
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.validate_timestamps=0
vim /etc/mysql/mariadb.conf.d/50-server.cnf
[mysqld]
innodb_buffer_pool_size = 2G
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
max_connections = 300
query_cache_type = 0
query_cache_size = 0
table_open_cache = 2000
tmp_table_size = 64M
max_heap_table_size = 64M
skip-name-resolve
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=phpcache:200m inactive=60m max_size=1g;
fastcgi_cache phpcache;
fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 404 1m;
apt install redis-server php-redis
session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379"
ufw allow 22
ufw allow 80
ufw allow 443
ufw enable
apt install fail2ban
display_errors = Off
log_errors = On
top
htop
iotop
free -h
ss -antp
nginx -t
php-fpm8.x -t
如果你愿意,可以告诉我:
我可以给你一套 完全定制化的 LNMP 优化配置。