LAMP (Linux, Apache, MySQL, PHP) 是常见的Web服务堆栈,以下是全面的性能优化建议:
内核参数调优:
# /etc/sysctl.conf 添加或修改
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_max_syn_backlog = 8192
net.core.somaxconn = 65535
vm.swappiness = 10
执行 sysctl -p
使生效
文件描述符限制:
# /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
nice
和 ionice
调整进程优先级cgroups
限制资源使用MPM模块选择:
event
或 worker
prefork
示例 event 配置:
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 10000
</IfModule>
启用 mod_deflate
压缩:
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
启用 mod_expires
缓存控制:
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
KeepAlive
但合理设置超时:
apache
KeepAlive On
KeepAliveTimeout 2
MaxKeepAliveRequests 100
# /etc/my.cnf 或 /etc/mysql/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已移除
max_connections = 200
thread_cache_size = 50
table_open_cache = 4000
OPTIMIZE TABLE
或使用 pt-online-schema-change
; /etc/php.ini
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
realpath_cache_size=4096K
realpath_cache_ttl=600
; 根据应用调整
memory_limit = 128M
max_execution_time = 30
ini
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 10
缓存策略:
内容分发:
监控工具:
top
, htop
, vmstat
, iostat
apachetop
, mytop
替代方案考虑:
mod_security
和 mod_evasive
实施这些优化后,建议使用工具如 ab
, siege
或 jmeter
进行压力测试,验证优化效果并根据实际负载进一步调整。