LAMP (Linux + Apache + 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_keepalive_time = 300
net.core.somaxconn = 262144
net.core.netdev_max_backlog = 262144
vm.swappiness = 10
文件系统优化
noatime,nodiratime
挂载选项echo 3 > /proc/sys/vm/drop_caches
清理缓存资源限制调整
# 编辑/etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
MPM模块选择
# 预fork模式(适合PHP)
<IfModule prefork.c>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxClients 150
MaxRequestsPerChild 4000
</IfModule>
# 或event模式(适合高并发)
<IfModule event.c>
ServerLimit 16
StartServers 2
MaxClients 400
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestsPerChild 0
</IfModule>
模块优化
mod_rewrite
, mod_ssl
等按需启用mod_deflate
mod_expires
, mod_headers
KeepAlive设置
KeepAlive On
KeepAliveTimeout 2
MaxKeepAliveRequests 100
配置优化(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 = 0 # MySQL 8.0已移除
tmp_table_size = 64M
max_heap_table_size = 64M
table_open_cache = 4000
索引优化
EXPLAIN
分析查询OPTIMIZE TABLE table_name
连接池优化
max_connections = 200
thread_cache_size = 50
wait_timeout = 300
PHP-FPM配置
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 10
pm.max_requests = 500
OPcache启用
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
其他优化
memory_limit
(如256M)realpath_cache_size = 256k
缓存策略
监控工具
定期维护
安全优化
通过以上优化措施,可以显著提升LAMP环境的性能和稳定性。建议每次修改后都进行压力测试(如使用ab, siege等工具)以验证优化效果。