温馨提示×

怎样优化 linux lnmp

小樊
39
2026-09-12 14:28:45
栏目: 智能运维

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


一、系统层优化

1. 系统参数调优(/etc/sysctl.conf)

net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 8192
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

3. 禁用不必要的服务

systemctl disable --now postfix
systemctl disable --now bluetooth

二、Nginx 优化

1. worker 配置(nginx.conf)

worker_processes auto;
worker_rlimit_nofile 65535;

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

2. 开启 gzip

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

3. 静态资源缓存

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

4. 开启 HTTP/2

listen 443 ssl http2;

三、PHP 优化(PHP-FPM)

1. PHP-FPM 进程模型

www.conf

pm = dynamic
pm.max_children = 100
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30

高并发可改为 pm = static

2. 关闭危险函数

disable_functions = exec,passthru,shell_exec,system

3. OPcache 开启(强烈推荐)

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

四、MySQL / MariaDB 优化

1. 基础参数(my.cnf)

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

2. 定期分析慢查询

SHOW FULL PROCESSLIST;

3. 使用连接池(可选)

  • ProxySQL
  • MySQL Router

五、缓存与加速

1. Redis 缓存

yum install redis
systemctl enable --now redis

PHP 使用:

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

2. Nginx 微缓存(动态页)

fastcgi_cache_path /tmp/nginx_cache levels=1:2 keys_zone=PHP:100m;

六、安全优化

  • 禁用 root SSH 登录
  • 改 SSH 端口
  • 配置防火墙(firewalld / iptables)
  • 定期更新系统
yum update -y

七、监控与压测

监控

  • htop
  • iotop
  • netstat -anp | grep nginx
  • mysqltuner

压测

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

八、典型优化效果

  • QPS 提升 2~5 倍
  • 响应时间降低 30%~70%
  • CPU / 内存更平稳

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

  • 服务器配置(CPU / 内存)
  • 使用的 LNMP 版本
  • 网站 / API / 商城 / 论坛

我可以给你一套 定制化优化配置

0