在 Ubuntu 上优化 LNMP(Linux + Nginx + MySQL/MariaDB + PHP),可以从系统层、Nginx、PHP、MySQL、缓存、安全与监控几个方面来做。下面是一套实用、可落地的优化方案。
systemctl disable bluetooth
systemctl disable cups
只保留 SSH、Nginx、PHP-FPM、MySQL。
ulimit -n 65535
永久生效:
/etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
/etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
vm.swappiness = 10
生效:
sysctl -p
worker_processes auto;
worker_connections 10240;
gzip on;
gzip_comp_level 5;
gzip_min_length 1k;
gzip_types text/css application/javascript application/json image/svg+xml;
location ~* \.(jpg|css|js|png)$ {
expires 30d;
access_log off;
}
server_tokens off;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
推荐 PHP 8.1 / 8.2 / 8.3
/etc/php/8.x/fpm/pool.d/www.conf
pm = dynamic
pm.max_children = 120
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 40
(根据内存调整:每个 PHP 进程约 30–80MB)
disable_functions = exec,passthru,shell_exec,system
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
[mysqld]
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
max_connections = 300
query_cache_type = 0
buffer_pool_size 建议为物理内存的 60–70%
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
apt install redis-server
PHP 使用:
session.save_handler = redis
ufw allow 22
ufw allow 80
ufw allow 443
ufw enable
apt update && apt upgrade -y
htopnetdataprometheus + grafanaab -n 10000 -c 200 http://domain.com/
| 场景 | 建议 |
|---|---|
| 小型博客 | 1核1G + PHP8 + Redis |
| 中型网站 | 2核4G + Nginx + OPcache |
| 高并发 | 4核8G+ + 多 PHP-FPM + CDN |
如果你愿意,可以告诉我:
我可以给你一份完全针对你服务器的配置示例。