在 Ubuntu 上优化 LAMP(Linux + Apache + MySQL/MariaDB + PHP)性能,通常从系统层、Apache、MySQL、PHP、缓存与运维几个方面入手。下面给你一套实用且可落地的优化方案。
systemctl list-unit-files --type=service | grep enabled
关闭不需要的服务(如 bluetooth, cups 等)。
ulimit -n
建议设为 65535:
echo "* soft nofile 65535" >> /etc/security/limits.conf
echo "* hard nofile 65535" >> /etc/security/limits.conf
noatime:/dev/sda1 / ext4 defaults,noatime 0 0
查看当前 MPM:
apache2ctl -V | grep MPM
启用 event:
a2dismod mpm_prefork
a2enmod mpm_event
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 1000
</IfModule>
apache2ctl -M
禁用无用模块:
a2dismod status autoindex cgi
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 2
apt install mysqltuner
mysqltuner
编辑 /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
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
apt install php-fpm
Apache 使用 proxy_fcgi:
a2enmod proxy_fcgi setenvif
a2enconf php8.1-fpm
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
disable_functions = exec,passthru,shell_exec,system
apt install php-opcache
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
apt install redis-server
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
a2enmod http2
ufw allow 22,80,443/tcp
ufw enable
htop
iotop
netdata
ab -n 1000 -c 100 http://localhost/
✅ 必做:
⚡ 进阶:
如果你愿意,可以告诉我:
我可以给你一套针对性配置。