温馨提示×

debian lnmp怎么优化

小樊
45
2026-07-30 08:07:26
栏目: 智能运维

在 Debian 上优化 LNMP(Linux + Nginx + MySQL/MariaDB + PHP),一般从 系统、Nginx、PHP、MySQL/MariaDB、缓存、安全 六个层面来做。下面给你一套实战型优化方案,适合生产环境。


一、系统层面优化

1. 调整系统资源限制

ulimit -n

建议至少:

ulimit -n 65535

永久生效:

vim /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535

2. 内核参数优化

vim /etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
vm.swappiness = 10

生效:

sysctl -p

二、Nginx 优化

1. worker 进程优化

worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;

events {
    worker_connections 10240;
    use epoll;
}

2. 连接与缓冲优化

keepalive_timeout 65;
client_max_body_size 50m;

sendfile on;
tcp_nopush on;
tcp_nodelay on;

3. 开启 Gzip

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

4. 静态资源缓存

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

三、PHP 优化(PHP-FPM)

1. PHP-FPM 进程管理

vim /etc/php/8.x/fpm/pool.d/www.conf

推荐配置(4 核 8G 示例):

pm = dynamic
pm.max_children = 80
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30
pm.max_requests = 1000

2. PHP 基础优化

memory_limit = 256M
upload_max_filesize = 50M
post_max_size = 50M
max_execution_time = 120
opcache.enable=1

3. 开启 Opcache

opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=0

四、MySQL / MariaDB 优化

1. 使用 InnoDB

SHOW ENGINES;

2. 常见 my.cnf 优化(4G 内存示例)

[mysqld]
innodb_buffer_pool_size = 2G
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
max_connections = 200
query_cache_type = 0

8G 内存可把 innodb_buffer_pool_size 设为 4G


3. 关闭无用功能

skip-name-resolve

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

1. Redis(推荐)

apt install redis

PHP:

apt install php-redis

用于:

  • 会话缓存
  • 页面缓存
  • 数据库缓存

2. Nginx 缓存(可选)

proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=phpcache:200m inactive=60m max_size=1g;

六、安全与稳定性

1. 防火墙

ufw allow 22
ufw allow 80
ufw allow 443
ufw enable

2. 关闭不必要服务

systemctl disable telnet

3. 使用 HTTPS

  • Let’s Encrypt
apt install certbot python3-certbot-nginx
certbot --nginx

七、性能检测工具

htop
iotop
vmstat 1

Nginx 状态:

stub_status on;

八、常见性能瓶颈判断

现象 原因
CPU 高 PHP 运算重
内存高 MySQL / PHP-FPM
磁盘 IO 高 没开 InnoDB 缓冲
并发低 Nginx / PHP-FPM 配置

九、推荐组合(稳定 + 高性能)

✅ Debian 11/12
✅ Nginx + PHP-FPM
✅ MariaDB + InnoDB
✅ Redis
✅ Opcache


如果你愿意,可以告诉我:

  • 服务器配置(CPU / 内存)
  • 网站类型(WordPress / Laravel / API)
  • 并发量

我可以给你一套 精准参数配置

0