优化 CentOS 上的 LAMP(Linux + Apache + MySQL/MariaDB + PHP)速度,可以从 系统层、Apache、MySQL/MariaDB、PHP、磁盘/网络 等多个层面入手。下面给你一套比较实用、可落地的优化方案(适合生产环境)。
systemctl list-unit-files --type=service | grep enabled
systemctl disable 不需要的服务
vi /etc/security/limits.conf
添加:
* soft nofile 65535
* hard nofile 65535
free -h
如果没 swap,建议加 2–4G:
dd if=/dev/zero of=/swapfile bs=1M count=2048
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
httpd -V | grep MPM
如果是 prefork,改成 event:
vi /etc/httpd/conf.modules.d/00-mpm.conf
启用:
LoadModule mpm_event_module modules/mod_mpm_event.so
vi /etc/httpd/conf/httpd.conf
示例(2–4 核服务器):
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 1000
</IfModule>
httpd -M
注释掉不需要的模块(如 WebDAV、proxy 等)
vi /etc/my.cnf
[mysqld]
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2
query_cache_type = 0
query_cache_size = 0
max_connections = 150
table_open_cache = 400
⚠️
innodb_buffer_pool_size建议设为内存的 50–70%
systemctl restart mariadb
yum install php-fpm
vi /etc/php-fpm.d/www.conf
关键参数:
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
yum install php-opcache
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
<FilesMatch \.php$>
SetHandler "proxy:fcgi://127.0.0.1:9000"
</FilesMatch>
LoadModule deflate_module modules/mod_deflate.so
<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>
mount -o remount,noatime /
mount -t tmpfs tmpfs /tmp
| 场景 | 推荐 |
|---|---|
| 页面缓存 | Varnish |
| 对象缓存 | Redis |
| 数据库缓存 | MySQL 查询缓存(已废弃,用 Redis) |
top
htop
iotop
vmstat 1
mysqltuner
✅ CentOS 7/8 + Apache(event) + PHP-FPM + MariaDB + OPcache + Redis
如果你愿意,可以告诉我:
我可以给你一套 针对你服务器的精准优化参数。