LNMP (Linux + Nginx + MySQL + PHP) 是常见的Web服务架构,以下是全面的性能优化建议:
内核参数调优
# 编辑/etc/sysctl.conf
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_max_tw_buckets = 5000
net.ipv4.ip_local_port_range = 1024 65000
fs.file-max = 65535
文件描述符限制
# /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
禁用不必要的服务
systemctl stop postfix
systemctl disable postfix
worker配置
worker_processes auto; # 与CPU核心数相同
worker_rlimit_nofile 65535;
events {
worker_connections 65535;
use epoll;
multi_accept on;
}
缓冲与超时设置
client_body_buffer_size 128k;
client_max_body_size 10m;
client_header_buffer_size 4k;
large_client_header_buffers 4 32k;
keepalive_timeout 65;
send_timeout 60;
Gzip压缩
gzip on;
gzip_min_length 1k;
gzip_comp_level 4;
gzip_types text/plain text/css application/json application/javascript text/xml;
静态文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
access_log off;
}
my.cnf配置
[mysqld]
innodb_buffer_pool_size = 4G # 总内存的50-70%
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2 # 非关键业务可设为2
innodb_flush_method = O_DIRECT
query_cache_size = 64M
max_connections = 500
定期维护
ANALYZE TABLE table_name;
OPTIMIZE TABLE table_name;
索引优化
php-fpm配置
pm = dynamic
pm.max_children = 100
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30
pm.max_requests = 1000 # 防止内存泄漏
php.ini优化
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
realpath_cache_size=4096K
realpath_cache_ttl=600
使用OPcache
# 安装OPcache扩展
apt install php-opcache
使用缓存系统
CDN加速
监控与分析
ngxtop
或 goaccess
分析日志slow_query_log
分析慢查询xhgui
进行性能分析定期维护
通过以上优化措施,可以显著提升LNMP环境的性能和稳定性。建议根据实际服务器配置和应用特点进行针对性调整,并通过压力测试验证优化效果。