温馨提示×

Debian LNMP如何优化

小樊
45
2026-10-13 15:56:06
栏目: 智能运维

在 Debian 上优化 LNMP(Linux + Nginx + MySQL/MariaDB + PHP),可以从系统层、Nginx、PHP、MySQL、缓存、安全与监控几个维度来做。下面是一套比较实用的优化思路(适用于生产环境,Debian 11/12 均可用)。


一、系统层优化(Debian)

1. 内核与文件描述符

# 提高文件描述符限制
ulimit -n 65535

写入 /etc/security/limits.conf:

* soft nofile 65535
* hard nofile 65535

2. 内核参数优化(/etc/sysctl.conf)

net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 600
vm.swappiness = 10

执行:

sysctl -p

3. 使用性能模式

apt install cpufrequtils
cpufreq-set -g performance

二、Nginx 优化

1. worker 配置(nginx.conf)

worker_processes auto;
worker_rlimit_nofile 65535;

events {
    worker_connections 10240;
    use epoll;
    multi_accept on;
}

2. 开启高效传输

sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 30;

3. 开启 Gzip

gzip on;
gzip_min_length 1k;
gzip_comp_level 5;
gzip_types text/plain text/css application/json application/javascript;

4. 静态资源缓存

location ~* \.(js|css|png|jpg|jpeg|gif|ico|woff2)$ {
    expires 30d;
    access_log off;
}

5. PHP 反向代理优化

fastcgi_buffer_size 128k;
fastcgi_buffers 4 256k;
fastcgi_busy_buffers_size 256k;
fastcgi_connect_timeout 60s;

三、PHP(PHP-FPM)优化

1. 选择合适的 PHP 版本

建议使用 PHP 8.1 / 8.2 / 8.3

2. PHP-FPM 进程管理

/etc/php/8.2/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
pm.max_requests = 1000

3. 关闭无用功能

expose_php = Off
disable_functions = exec,passthru,shell_exec,system

4. OPcache 必开

opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60

四、MySQL / MariaDB 优化

1. 基础配置(/etc/mysql/my.cnf)

[mysqld]
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
max_connections = 300
query_cache_type = 0
slow_query_log = 1

2. 使用工具生成配置

apt install mariadb-server
wget https://raw.githubusercontent.com/major/MySQLTuner-perl/master/mysqltuner.pl
perl mysqltuner.pl

3. 定期优化表

OPTIMIZE TABLE table_name;

五、缓存层优化(强烈推荐)

1. Redis 缓存

apt install redis-server

PHP:

apt install php-redis

2. Nginx 微缓存(动态页)

fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=phpcache:100m;
fastcgi_cache phpcache;
fastcgi_cache_valid 200 10m;

六、安全与稳定性

1. 防火墙

ufw allow 22,80,443
ufw enable

2. 定期更新

apt update && apt upgrade -y

3. 日志与监控

  • htop
  • netdata
  • fail2ban

七、常见性能瓶颈排查顺序

  1. top / htop → CPU
  2. free -m → 内存
  3. iostat → 磁盘 IO
  4. nginx access log → 慢请求
  5. mysqltuner → 数据库

如果你愿意,我可以:

  • ✅ 根据你的 服务器配置(CPU/内存) 给具体参数
  • ✅ 针对 WordPress / Laravel / 自建 API 做专项优化
  • ✅ 给你一套 一键 LNMP 优化脚本

你可以告诉我你的 Debian 版本 + 业务类型。

0 踩