温馨提示×

centos lamp怎么优化内存

小樊
43
2026-10-03 07:21:34
栏目: 智能运维

在 CentOS 上优化 LAMP(Linux + Apache + MySQL/MariaDB + PHP)内存占用,核心思路是:减少不必要的服务、调小各组件资源消耗、使用轻量方案。下面按组件说明可落地的优化方法。


一、系统层面优化

1. 关闭不必要的服务

systemctl list-unit-files --type=service | grep enabled

常见可关的:

systemctl disable --now postfix
systemctl disable --now cups
systemctl disable --now bluetooth

2. 使用轻量登录 shell / 减少后台进程

  • 不装桌面环境(GNOME/KDE)
  • 用 minicom / screen 替代多余终端

3. 调整 SWAP(小内存机器)

free -h
swapon --show

小内存(≤2G)建议:

  • SWAP ≥ 1–2GB
  • 降低 swap 使用倾向(避免卡顿):
sysctl vm.swappiness=10
echo 'vm.swappiness=10' >> /etc/sysctl.conf

二、Apache 优化(重点)

1. 选择 MPM(推荐 event)

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

2. 限制进程数(关键)

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>

3. 关闭无用模块

httpd -M

注释掉不用的:

  • mod_status(非必要)
  • mod_userdir
  • mod_lua

4. 开启 KeepAlive 但限制

KeepAlive On
MaxKeepAliveRequests 50
KeepAliveTimeout 5

三、MySQL / MariaDB 优化

1. 使用轻量配置

编辑:

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

2. 使用 MariaDB 替代 MySQL

MariaDB 更轻量、CentOS 默认支持好。

3. 关闭性能_schema(小内存)

performance_schema = OFF

四、PHP 优化

1. 使用 PHP-FPM(比 mod_php 省内存)

yum install php-fpm

Apache 使用:

proxy_fcgi

2. 限制 PHP-FPM 进程

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

3. 禁用不必要扩展

php -m

常见可禁用:

  • gd(不用图片处理)
  • soap
  • xmlrpc

五、缓存与加速(反直觉但有效)

1. 开启 OPcache

yum install php-opcache
opcache.enable=1
opcache.memory_consumption=64

2. 使用 Redis 替代文件缓存(可选)

比频繁读磁盘更省 CPU。


六、监控与验证

查看内存占用

free -h
ps_mem
top -c

查看 Apache / PHP 占用

ps -ylC httpd
ps -ylC php-fpm

七、极端省内存方案(可选)

如果内存极小(≤512M):

  • 用 Nginx + SQLite + PHP
  • 或 Lighttpd
  • 不用 MySQL

如果你能提供:

  • CentOS 版本
  • 内存大小
  • 是否是生产环境

我可以给你一份可直接用的配置文件。

0 踩