在LAMP(Linux + Apache + MySQL + PHP)环境下优化Linux性能需要从系统层、服务层和应用层进行综合调整。以下是详细的优化方案:
内核参数调优
修改 /etc/sysctl.conf
,优化TCP/IP和内存管理:
# 提升网络性能
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
net.core.somaxconn = 65535
# 内存和文件系统优化
vm.swappiness = 10
vm.dirty_ratio = 60
vm.dirty_background_ratio = 10
fs.file-max = 65535
sysctl -p
文件系统优化
ext4
或 xfs
文件系统(推荐 xfs
对高并发更友好)。/etc/fstab
):
bash
defaults,noatime,nodiratime,data=writeback,barrier=0 1 1
资源限制调整
/etc/security/limits.conf
:
```bash
禁用不必要的服务
postfix
、bluetooth
):
bash
systemctl disable postfix
MPM模块选择
event
MPM(替换 prefork
):
bash
a2dismod mpm_prefork
a2enmod mpm_event
systemctl restart apache2
配置参数调整
/etc/apache2/mods-available/mpm_event.conf
:
apache
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 1000
启用压缩与缓存
mod_deflate
和 mod_expires
:
apache
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml application/json
</IfModule>
配置 my.cnf
ini
[mysqld]
innodb_buffer_pool_size = 2G # 内存的50%-70%
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2 # 非严格ACID场景可设为2
query_cache_size = 0 # MySQL 8.0已移除查询缓存
max_connections = 200
索引与查询优化
EXPLAIN
分析慢查询,添加合适的索引。ini
slow_query_log = 1
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = 2
OPcache加速
OPcache
(PHP 7+默认集成):
ini
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=4000
调整PHP-FPM配置
/etc/php/7.x/fpm/pool.d/www.conf
:
ini
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 10
使用缓存层
监控与诊断工具
bash
top/htop # 实时系统负载
vmstat 1 # 监控CPU/内存/IO
iostat -x 1 # 磁盘IO分析
mysqladmin proc # MySQL进程监控
定期维护
logrotate
)。ufw
/iptables
)限制非必要端口。mod_security
加固Apache。通过以上步骤,LAMP环境的性能可显著提升。建议每次修改后通过工具(如 ab
、sysbench
)进行压力测试,对比优化效果。根据实际硬件和业务需求调整参数值。