优化 Debian 上的 LAMP(Linux + Apache + MySQL/MariaDB + PHP) 可以从 系统层、Apache、数据库、PHP、安全、缓存 等多个维度进行。下面给你一套 实用、可落地的优化方案,适用于生产环境。
apt update && apt upgrade -y
systemctl list-units --type=service --state=running
systemctl disable 不需要的服务
vi /etc/security/limits.conf
添加:
* soft nofile 65535
* hard nofile 65535
vi /etc/sysctl.conf
示例:
net.core.somaxconn = 65535
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
vm.swappiness = 10
应用:
sysctl -p
apt install apache2
查看当前 MPM:
apache2ctl -M | grep mpm
推荐:
切换:
a2dismod mpm_prefork
a2enmod mpm_event
vi /etc/apache2/mods-available/mpm_event.conf
示例(2G 内存服务器):
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 1000
</IfModule>
apache2ctl -M
a2dismod autoindex cgi status
vi /etc/apache2/apache2.conf
KeepAlive On
KeepAliveTimeout 5
MaxKeepAliveRequests 100
a2enmod deflate
a2enmod headers
示例:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
apt install php-fpm
a2enmod proxy_fcgi setenvif
a2enconf php-fpm
vi /etc/php/*/fpm/pool.d/www.conf
推荐:
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
vi /etc/php/*/fpm/php.ini
disable_functions = exec,passthru,shell_exec,system,proc_open
memory_limit = 256M
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 120
opcache.enable=1
apt install mariadb-server
vi /etc/mysql/mariadb.conf.d/50-server.cnf
示例(2G 内存):
innodb_buffer_pool_size = 512M
innodb_log_file_size = 128M
max_connections = 150
query_cache_type = 0
query_cache_size = 0
mysql_secure_installation
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
apt install redis-server php-redis
apt install ufw
ufw allow 22
ufw allow 80
ufw allow 443
ufw enable
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-Content-Type-Options "nosniff"
ServerTokens Prod
ServerSignature Off
apt install logrotate
htopiotopnetdataprometheus + grafana| 项目 | 优化前 | 优化后 |
|---|---|---|
| 并发 | 低 | 高 |
| 内存 | 高 | 低 |
| 响应时间 | 慢 | 快 |
| 稳定性 | 一般 | 高 |
如果你愿意,我可以:
直接告诉我你的 Debian 版本 + 服务器配置 + 使用场景 即可。