在 CentOS 上搭建 LAMP(Linux + Apache + MySQL/MariaDB + PHP) 后,访问速度慢是比较常见的问题。原因通常涉及 系统配置、网络、服务参数、资源瓶颈 等多个方面。下面按常见原因逐一分析,并给出对应的排查和优化建议。
Apache 默认会尝试对客户端 IP 做 反向 DNS 解析,如果 DNS 不通,会明显变慢。
排查
httpd -M | grep hostname
解决 编辑 Apache 配置:
vi /etc/httpd/conf/httpd.conf
修改或添加:
HostnameLookups Off
重启:
systemctl restart httpd
排查
ping your-server-ip
traceroute your-server-ip
prefork 模式且连接数过低CentOS 默认 Apache 多为 prefork。
查看:
httpd -V | grep MPM
优化 /etc/httpd/conf/httpd.conf 或 conf.modules.d/00-mpm.conf:
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 3000
</IfModule>
如果是高并发,可考虑改为 event 或 worker 模式。
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
Timeout 太长会占用连接。
PHP 每次请求都重新编译,会非常慢。
安装 OPcache
yum install php-opcache
启用:
; /etc/php.ini
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=4000
重启:
systemctl restart php-fpm # 或 httpd
display_errors = Off
log_errors = On
开启 PHP 慢日志:
slowlog = /var/log/php-fpm/slow.log
request_slowlog_timeout = 2s
排查
SHOW PROCESSLIST;
开启慢查询日志:
slow_query_log = 1
slow_query_log_file = /var/log/mariadb/slow.log
long_query_time = 1
MySQL 使用 localhost 会走 socket,有时反而慢。
PHP 中:
mysqli_connect("127.0.0.1", "user", "pass");
free -h
top
如果 swap 使用高:
虽然一般不会“很慢”,但某些情况下会卡。
临时测试:
setenforce 0
Apache 开启:
<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"
</IfModule>
你可以按顺序确认:
如果你愿意,可以直接告诉我:
我可以帮你做更精准的排查。