在 CentOS 上优化 LAMP(Linux + Apache + MySQL/MariaDB + PHP)内存占用,核心思路是:减少不必要的服务、调小各组件资源消耗、使用轻量方案。下面按组件说明可落地的优化方法。
systemctl list-unit-files --type=service | grep enabled
常见可关的:
systemctl disable --now postfix
systemctl disable --now cups
systemctl disable --now bluetooth
minicom / screen 替代多余终端free -h
swapon --show
小内存(≤2G)建议:
sysctl vm.swappiness=10
echo 'vm.swappiness=10' >> /etc/sysctl.conf
httpd -V | grep MPM
CentOS 7/8 推荐:
yum install mod_http2
修改:
vi /etc/httpd/conf.modules.d/00-mpm.conf
启用:
LoadModule mpm_event_module modules/mod_mpm_event.so
vi /etc/httpd/conf/httpd.conf
示例(1–2G 内存):
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 1000
</IfModule>
httpd -M
注释掉不用的:
KeepAlive On
MaxKeepAliveRequests 50
KeepAliveTimeout 5
编辑:
vi /etc/my.cnf.d/server.cnf
或 /etc/my.cnf
小内存示例(1G):
[mysqld]
innodb_buffer_pool_size = 128M
key_buffer_size = 16M
max_connections = 50
query_cache_size = 0
table_open_cache = 256
tmp_table_size = 32M
max_heap_table_size = 32M
MariaDB 更轻量、CentOS 默认支持好。
performance_schema = OFF
yum install php-fpm
Apache 使用:
proxy_fcgi
vi /etc/php-fpm.d/www.conf
示例:
pm = dynamic
pm.max_children = 10
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
php -m
常见可禁用:
yum install php-opcache
opcache.enable=1
opcache.memory_consumption=64
比频繁读磁盘更省 CPU。
free -h
ps_mem
top -c
ps -ylC httpd
ps -ylC php-fpm
如果内存极小(≤512M):
如果你能提供:
我可以给你一份可直接用的配置文件。