LAMP(Linux+Apache+MySQL+PHP)是常见的Web服务器架构,以下是从各个组件出发的性能优化建议:
# 增加文件描述符限制
echo "* soft nofile 65535" >> /etc/security/limits.conf
echo "* hard nofile 65535" >> /etc/security/limits.conf
# 调整内核参数
echo "net.ipv4.tcp_fin_timeout = 30" >> /etc/sysctl.conf
echo "net.ipv4.tcp_keepalive_time = 300" >> /etc/sysctl.conf
echo "net.ipv4.tcp_tw_reuse = 1" >> /etc/sysctl.conf
echo "net.ipv4.tcp_tw_recycle = 1" >> /etc/sysctl.conf
echo "net.ipv4.ip_local_port_range = 1024 65000" >> /etc/sysctl.conf
sysctl -p
# 选择合适的工作模式
# prefork模式(适合PHP)
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 10000
# 或者event/worker模式(适合高并发)
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 10000
# 其他重要参数
KeepAlive On
KeepAliveTimeout 2
MaxKeepAliveRequests 100
Timeout 30
HostnameLookups Off
EnableSendfile Off # 对NFS禁用
mod_negotiation, mod_status, mod_info等mod_cache, mod_expires, mod_deflate[mysqld]
# 内存相关
key_buffer_size = 256M
innodb_buffer_pool_size = 1G # 物理内存的50-70%
query_cache_size = 64M
query_cache_limit = 4M
# InnoDB优化
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2 # 对性能要求高时可设为2(牺牲部分持久性)
innodb_flush_method = O_DIRECT
innodb_file_per_table = 1
# 连接相关
max_connections = 200
thread_cache_size = 50
table_open_cache = 2000
OPTIMIZE TABLE tablenamememory_limit = 128M
max_execution_time = 30
post_max_size = 16M
upload_max_filesize = 16M
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
优化后务必进行压力测试(如使用ab, siege等工具)验证效果,并根据实际负载情况持续调整参数。