温馨提示×

怎样优化debian lnmp

小樊
41
2026-09-07 20:35:13
栏目: 智能运维

优化 Debian 上的 LNMP(Linux + Nginx + MySQL/MariaDB + PHP) 通常从系统层、Nginx、PHP、MySQL、缓存、安全与监控几个方面入手。下面给你一套实用、可落地的优化清单,适合生产环境。


一、系统层优化(Debian)

1. 更新系统与内核参数

apt update && apt upgrade -y

编辑 /etc/sysctl.conf

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

执行:

sysctl -p

2. 文件描述符限制

编辑 /etc/security/limits.conf

* soft nofile 65535
* hard nofile 65535

二、Nginx 优化

1. worker 配置(nginx.conf)

worker_processes auto;
worker_rlimit_nofile 65535;

events {
    worker_connections 10240;
    use epoll;
}

2. 开启 Gzip

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

3. 静态资源缓存

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

4. 关闭无用日志(高并发)

access_log off;

三、PHP(PHP-FPM)优化

1. PHP-FPM 进程模型

编辑:

/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

若是高并发 API,可改为 pm = static

2. 禁用危险函数

disable_functions = exec,passthru,shell_exec,system

3. OPcache 必开

opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=4000

四、MySQL / MariaDB 优化

1. 基础优化(my.cnf)

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

内存小可改为 512M

2. 慢查询日志

slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1

3. 定期优化表

OPTIMIZE TABLE table_name;

五、缓存加速

1. Redis(强烈推荐)

apt install redis-server

PHP 使用:

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

2. Nginx + Redis 缓存页面(可选)

适合内容站、API 缓存


六、安全优化

1. 防火墙

ufw allow 22,80,443
ufw enable

2. 隐藏版本

server_tokens off;

3. 防止恶意扫描

limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

七、监控与维护

  • htop
  • netdata
  • mysqltuner
  • 日志:
    • /var/log/nginx/
    • /var/log/php-fpm.log

八、推荐组合(性能最好)

✅ Debian 12
✅ Nginx
✅ PHP 8.2+
✅ MariaDB
✅ Redis
✅ OPcache


如果你愿意,我可以:

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

你现在是哪种业务场景?

0