温馨提示×

怎样优化linux lnmp

小樊
42
2026-09-03 14:53:10
栏目: 智能运维

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


一、系统层优化(基础)

1. 内核与文件描述符

# 修改文件限制
/etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535

# 内核参数
/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. 关闭无用服务

systemctl disable postfix firewalld --now
# 若用 iptables 或云安全组替代

3. 使用 SSD + 合理分区

  • /var/lib/mysql
  • /usr/local/nginx/logs 放 SSD,提升 IO。

二、Nginx 优化

1. worker 配置

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/css application/javascript application/json image/svg+xml;

3. 静态资源缓存

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

4. 开启 FastCGI 缓存(可选)

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

三、PHP 优化(PHP-FPM)

1. PHP-FPM 进程管理

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

2. 禁用危险函数

disable_functions = exec,passthru,shell_exec,system

3. OPcache 必开

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

四、MySQL / MariaDB 优化

1. 基础参数(示例 4G 内存)

innodb_buffer_pool_size = 2G
innodb_log_file_size = 256M
max_connections = 500
query_cache_type = 0

2. 慢查询日志

slow_query_log = 1
long_query_time = 1

3. 定期优化表

OPTIMIZE TABLE table_name;

五、缓存层优化(非常重要)

1. Redis 缓存

  • 页面缓存
  • Session 存储
  • 数据库查询结果缓存

2. 使用 CDN

  • 静态资源走 CDN
  • 减少源站压力

六、架构级优化(高并发)

  • Nginx + PHP-FPM 分离
  • 数据库主从
  • 读写分离
  • 队列(RabbitMQ / Redis Queue)

七、监控与排查工具

top / htop
iotop
netstat -anp | grep nginx
mysqltuner
php-fpm status

八、快速检查清单 ✅

  • [ ] 文件描述符已调大
  • [ ] Nginx worker 合理
  • [ ] PHP OPcache 已开
  • [ ] MySQL buffer pool 合理
  • [ ] 静态资源有缓存
  • [ ] 有监控手段

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

  • 服务器配置(CPU / 内存)
  • 访问量(PV / QPS)
  • 用的 PHP 版本 & 框架

我可以给你一套精准参数模板。

0 踩