在 CentOS 上搭建 LAMP(Linux + Apache + MySQL/MariaDB + PHP) 后访问缓慢,原因通常集中在系统配置、服务参数、网络、资源瓶颈等方面。下面按常见原因 → 排查方法 → 解决建议系统性说明。
prefork 且进程数不足CentOS 默认 Apache 多用 prefork:
httpd -V | grep -i mpm
现象:并发稍高就卡死。
解决: 编辑:
vim /etc/httpd/conf.modules.d/00-mpm.conf
示例(prefork):
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 3000
或切换为 event(推荐):
LoadModule mpm_event_module modules/mod_mpm_event.so
重启:
systemctl restart httpd
vim /etc/httpd/conf/httpd.conf
建议:
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
PHP 每次请求都重新编译,极慢。
检查:
php -m | grep opcache
安装:
yum install php-opcache -y
配置 /etc/php.d/opcache.ini:
opcache.enable=1
opcache.memory_consumption=128
opcache.revalidate_freq=60
mod_php 而非 php-fpmCentOS 7+ 推荐:
yum install php-fpm
systemctl enable php-fpm
Apache 使用 proxy_fcgi 模式。
开启慢查询日志:
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
show variables like 'max_connections';
修改:
[mysqld]
max_connections = 200
示例:
innodb_buffer_pool_size = 512M
query_cache_size = 0
Apache 默认做反向 DNS:
HostnameLookups Off
否则每请求一次卡几百毫秒。
临时测试:
setenforce 0
永久:
vim /etc/selinux/config
SELINUX=disabled
只开放必要端口:
firewall-cmd --list-all
iostat -x 1
若 %util 接近 100%,说明磁盘瓶颈。
du -sh /var/log/httpd
查看:
ethtool eth0
# 1. 看负载
top
# 2. 看 Apache 连接
ss -ant | grep :80 | wc -l
# 3. 看 MySQL
mysqladmin processlist
# 4. 看 PHP
php -v
php -m | grep opcache
# 5. 看日志
tail -f /var/log/httpd/error_log
✅ Apache 进程不够
✅ PHP 没开 OPcache
✅ MySQL 没索引
✅ DNS 反向解析
✅ 云服务器带宽小
✅ 用了 HDD 而非 SSD
如果你愿意,可以告诉我:
我可以直接给你针对性优化配置。