在 CentOS 上优化 LAMP(Linux + Apache + MySQL/MariaDB + PHP)环境,可以从系统层、Apache、MySQL/MariaDB、PHP、缓存与运维几个方面入手。下面给出一套实用、可落地的优化方案(适用于 CentOS 7/8、生产环境)。
systemctl disable --now postfix
systemctl disable --now firewalld # 如有外部防火墙可关
保留:sshd、crond、network
vi /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
vi /etc/sysctl.conf
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 8192
vm.swappiness = 10
sysctl -p
httpd -V | grep MPM
如不是 event:
vi /etc/httpd/conf.modules.d/00-mpm.conf
LoadModule mpm_event_module modules/mod_mpm_event.so
vi /etc/httpd/conf.d/mpm.conf
示例(4核8G):
<IfModule mpm_event_module>
StartServers 4
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 64
MaxRequestWorkers 512
MaxConnectionsPerChild 10000
</IfModule>
注释掉不需要的模块(如 mod_userdir、mod_status 非必要)
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 30 days"
ExpiresByType text/css "access plus 7 days"
</IfModule>
yum install mariadb-server
编辑:
vi /etc/my.cnf.d/server.cnf
示例(4G内存):
[mysqld]
innodb_buffer_pool_size = 2G
innodb_log_file_size = 256M
max_connections = 300
query_cache_type = 0
slow_query_log = 1
slow_query_log_file = /var/log/mariadb/slow.log
long_query_time = 1
mysqldumpslow -s t /var/log/mariadb/slow.log
yum install php-fpm
vi /etc/php-fpm.d/www.conf
pm = dynamic
pm.max_children = 100
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30
Apache 使用:
ProxyPassMatch ^/(.*\.php)$ unix:/run/php-fpm/www.sock|fcgi://localhost/var/www/html/$1
disable_functions = exec,passthru,shell_exec,system
yum install php-opcache
opcache.enable=1
opcache.memory_consumption=128
opcache.revalidate_freq=60
yum install redis
systemctl enable --now redis
PHP 使用 Redis 缓存 session / 数据。
yum install certbot python2-certbot-apache
certbot --apache
logrotate 自动切割htop、iotop、netdatayum update -y
如果你愿意,我可以:
你现在的 CentOS 版本和服务器配置是多少?