CentOS LAMP 资源占用优化实战指南
一 系统层优化
* soft nofile 65535
* hard nofile 65535
* soft nproc 65535
* hard nproc 65535
mysql soft nofile 65535
mysql hard nofile 65535
apache soft nofile 65535
apache hard nofile 65535
fs.file-max = 1000000
sysctl -pnet.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 0 # NAT/负载均衡环境务必为0
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_max_tw_buckets = 20000
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 16384 16777216
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.netdev_max_backlog = 30000
net.ipv4.tcp_max_syn_backlog = 4096
net.core.somaxconn = 4096
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_orphans = 262144
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_slow_start_after_idle = 0
vm.swappiness = 0
vm.dirty_background_ratio = 5
vm.dirty_ratio = 10
cat /sys/block/sda/queue/scheduler
echo deadline > /sys/block/sda/queue/scheduler # SSD/通用推荐
# 或 echo noop > /sys/block/sda/queue/scheduler
二 Apache 优化
yum install -y httpd-eventLoadModule mpm_event_module modules/mod_mpm_event.so
ServerLimit 256
StartServers 8
MinSpareThreads 64
MaxSpareThreads 256
ThreadsPerChild 64
MaxRequestWorkers 2048
MaxConnectionsPerChild 10000
Timeout 30
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 2
EnableSendfile On
LoadModule deflate_module modules/mod_deflate.so
DeflateCompressionLevel 6
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
LogLevel warn
CustomLog "|/usr/sbin/rotatelogs /var/log/httpd/access_log.%Y%m%d 86400" combined
# 禁用不需要的模块(如 HostnameLookups Off)
三 MySQL MariaDB 优化
[mysqld]
max_connections = 1000
skip-name-resolve = 1
innodb_buffer_pool_size = 8G
innodb_buffer_pool_instances = 8
innodb_flush_method = O_DIRECT
innodb_flush_log_at_trx_commit = 2
innodb_log_file_size = 256M
innodb_log_buffer_size = 16M
innodb_file_per_table = 1
query_cache_type = 0
query_cache_size = 0
tmp_table_size = 64M
max_heap_table_size = 64M
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
log_queries_not_using_indexes = 0
四 PHP 与缓存层优化
[www]
pm = dynamic
pm.max_children = 150
pm.start_servers = 10
pm.min_spare_servers = 10
pm.max_spare_servers = 30
pm.max_requests = 500
request_terminate_timeout = 30
listen.backlog = 4096
rlimit_files = 65535
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.validate_timestamps=0 # 生产建议关闭,部署时再开启
opcache.revalidate_freq=0
五 监控验证与回滚
top/htop、vmstat 1、iostat -x 1、sar -n DEV 1ss -s、netstat -anp | grep :80 | wc -lmysqladmin status、SHOW PROCESSLIST;、SHOW ENGINE INNODB STATUS\G