温馨提示×

debian lnmp怎样优化性能

小樊
42
2026-09-10 18:33:33
栏目: 智能运维

在 Debian 上搭建的 LNMP(Linux + Nginx + MySQL/MariaDB + PHP) 环境,性能优化通常从 系统层、Nginx、PHP、MySQL、缓存、监控 六个方面入手。下面给你一套实用、可落地的优化方案(适合生产环境)。


一、系统层优化(基础)

1. 调整 Linux 内核参数

编辑 /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

2. 文件描述符限制

ulimit -n 65535

编辑 /etc/security/limits.conf:

* soft nofile 65535
* hard nofile 65535

二、Nginx 优化

1. worker 进程

worker_processes auto;
worker_rlimit_nofile 65535;

2. events 模块

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

3. http 层优化

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 30;
    gzip on;
    gzip_min_length 1k;
    gzip_comp_level 5;
    gzip_types text/css application/javascript image/svg+xml;
}

4. 静态资源缓存

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

三、PHP(PHP-FPM)优化

1. PHP-FPM 进程模式

编辑:

/etc/php/*/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

内存估算:
max_children × 单个PHP进程内存(一般 30~80MB)

2. 关闭不必要的功能

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

3. OPcache(非常重要)

opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
opcache.validate_timestamps=0

四、MySQL / MariaDB 优化

1. 使用 my.cnf 配置

示例(2G~4G 内存服务器):

[mysqld]
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
max_connections = 300
query_cache_type = 0
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1

2. 定期分析慢查询

SHOW PROCESSLIST;

五、缓存加速(强烈推荐)

1. 前端缓存

  • Nginx FastCGI Cache
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=PHP:100m;

2. 应用层缓存

  • Redis
  • Memcached

Debian 安装:

apt install redis-server

六、监控与压测

1. 监控工具

  • htop
  • iotop
  • netdata
  • Prometheus + Grafana

2. 压力测试

ab -n 10000 -c 200 http://domain.com/

或:

wrk -t4 -c200 -d30s http://domain.com/

七、常见性能瓶颈总结

问题 原因 解决
CPU 高 PHP 逻辑重 OPcache + 代码优化
内存爆 FPM 过多 降低 max_children
磁盘 IO 高 日志 / 数据库 SSD + 缓存
连接数不够 系统限制 ulimit + sysctl

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

  • Debian 版本
  • 内存大小
  • 网站类型(WordPress / API / 商城)

我可以直接给你一份可复制的配置文件。

0 踩