温馨提示×

ubuntu lamp怎么优化性能

小樊
49
2026-10-27 12:46:30
栏目: 智能运维

在 Ubuntu 上优化 LAMP(Linux + Apache + MySQL/MariaDB + PHP)性能,通常从系统层、Apache、MySQL、PHP、缓存与运维几个方面入手。下面给你一套实用且可落地的优化方案。


一、系统层优化(基础)

1. 关闭不必要的服务

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

关闭不需要的服务(如 bluetooth, cups 等)。

2. 调整文件描述符

ulimit -n

建议设为 65535:

echo "* soft nofile 65535" >> /etc/security/limits.conf
echo "* hard nofile 65535" >> /etc/security/limits.conf

3. 使用 SSD + 合理的文件系统

  • ext4 / xfs
  • 挂载时加上 noatime:
/dev/sda1 / ext4 defaults,noatime 0 0

二、Apache 优化(重点)

1. 选择合适的 MPM(非常重要)

查看当前 MPM:

apache2ctl -V | grep MPM

推荐:

  • 高并发 → event
  • 老程序 → prefork

启用 event:

a2dismod mpm_prefork
a2enmod mpm_event

2. 调整 MPM 参数(示例,2核4G)

<IfModule mpm_event_module>
    StartServers             2
    MinSpareThreads         25
    MaxSpareThreads         75
    ThreadLimit             64
    ThreadsPerChild         25
    MaxRequestWorkers      150
    MaxConnectionsPerChild  1000
</IfModule>

3. 关闭多余模块

apache2ctl -M

禁用无用模块:

a2dismod status autoindex cgi

4. 开启 KeepAlive(适度)

KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 2

三、MySQL / MariaDB 优化

1. 使用配置工具

apt install mysqltuner
mysqltuner

2. 常见优化(4G内存示例)

编辑 /etc/mysql/mysql.conf.d/mysqld.cnf:

innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
query_cache_type = 0
max_connections = 200
table_open_cache = 2000

3. 慢查询日志

slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1

四、PHP 优化

1. 使用 PHP-FPM(推荐)

apt install php-fpm

Apache 使用 proxy_fcgi:

a2enmod proxy_fcgi setenvif
a2enconf php8.1-fpm

2. PHP-FPM 池优化

pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20

3. 禁用危险函数

disable_functions = exec,passthru,shell_exec,system

五、缓存加速(立竿见影)

1. OPcache(必开)

apt install php-opcache
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000

2. 页面缓存

  • WordPress → WP Super Cache / Redis
  • 通用 → Varnish / Nginx 反代

3. Redis / Memcached

apt install redis-server

六、网络与安全优化

1. 开启 Gzip

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>

2. 启用 HTTP/2

a2enmod http2

3. 防火墙

ufw allow 22,80,443/tcp
ufw enable

七、监控与压测

监控

htop
iotop
netdata

压测

ab -n 1000 -c 100 http://localhost/

八、简单总结(优先级)

✅ 必做:

  • 换 event MPM
  • 开 OPcache
  • 调 MySQL buffer
  • 用 PHP-FPM

⚡ 进阶:

  • Redis 缓存
  • CDN
  • 数据库读写分离

如果你愿意,可以告诉我:

  • Ubuntu 版本
  • 内存 / CPU
  • 用的是 WordPress 还是自研程序

我可以给你一套针对性配置。

0 踩