温馨提示×

linux lnmp怎么提速

小樊
42
2026-10-09 15:03:28
栏目: 智能运维

在 Linux 的 LNMP(Linux + Nginx + MySQL/MariaDB + PHP) 环境下,提速一般从 Nginx、PHP、MySQL、系统/磁盘、缓存 几个层面入手。下面给你一套实用、可落地的优化方案。


一、Nginx 优化(Web 层提速)

1. 调整 worker 进程

worker_processes auto;
worker_cpu_affinity auto;

查看 CPU 核数:

nproc

2. 连接与超时优化

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

http {
    keepalive_timeout 30;
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    client_max_body_size 20m;
}

3. 开启 Gzip 压缩

gzip on;
gzip_min_length 1k;
gzip_comp_level 6;
gzip_types text/css text/js application/json 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 进程配置

编辑:

vim /etc/php-fpm.d/www.conf

常见配置(根据内存调整):

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

查看内存:

free -h

2. 开启 OPcache(非常重要)

vim /etc/php.d/10-opcache.ini
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60

重启:

systemctl restart php-fpm

三、MySQL / MariaDB 优化

1. 修改配置文件

vim /etc/my.cnf

基础优化(2G~4G 内存):

[mysqld]
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
query_cache_type = 0
max_connections = 200
thread_cache_size = 50
table_open_cache = 2000

重启:

systemctl restart mysql

2. 慢查询日志

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

四、缓存加速(效果最明显)

1. Nginx 缓存(页面缓存)

proxy_cache_path /data/cache levels=1:2 keys_zone=mycache:10m max_size=1g;

2. Redis 缓存(推荐)

yum install redis -y
systemctl enable redis
systemctl start redis

PHP 使用 Redis 缓存 session / 数据。


五、系统层优化

1. 文件描述符

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_tw_reuse = 1
vm.swappiness = 10

生效:

sysctl -p

六、磁盘 & CDN

  • 使用 SSD
  • 静态资源放 CDN
  • 大文件、图片走对象存储(OSS / S3)

七、常见性能检测命令

top
htop
iotop
netstat -antp
php-fpm status
mysqltuner

八、推荐组合(最简单有效)

✅ Nginx + OPcache
✅ Redis 缓存
✅ Gzip + 静态缓存
✅ SSD + CDN


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

  • 服务器配置(CPU / 内存)
  • 用的是哪个 LNMP 一键包(LNMP.org / 宝塔 / 手动)
  • 网站类型(WordPress / 商城 / API)

我可以给你针对性参数。

0 踩