上一篇 下一篇 分享链接 返回 返回顶部

Debian 扛高并发实战:从内核调优到 Nginx 配置,一套命令搞定

发布人:慈云数据-客服中心 发布时间:7小时前 阅读量:0

Debian 高并发解决方案|附完整命令

在互联网业务中,高并发是服务器运维和后端架构绕不开的话题。无论是网站、电商系统、API 网关、文件下载服务,还是 WebSocket、短连接接口服务,只要访问量上来,服务器就可能出现响应变慢、连接失败、CPU 飙高、内存耗尽、端口不足、文件句柄不够、Nginx 502/504、数据库连接打满等问题。

Debian 作为稳定、轻量、安全性较高的 Linux 发行版,非常适合作为生产环境服务器系统。本文将以 Debian 为基础,系统讲解一套面向高并发场景的优化方案,并附上完整命令,方便直接落地使用。

适用系统:Debian 11 / Debian 12
适用场景:高并发 Web 服务、Nginx 反向代理、API 服务、静态资源服务、Node.js / Go / Java / PHP 后端服务等


一、高并发问题的核心瓶颈

在 Debian 服务器上,高并发通常不是单一问题,而是多个层面的综合瓶颈。

常见瓶颈包括:

  1. 系统文件句柄限制过低

    • 每个 TCP 连接、文件、Socket 都会占用文件描述符。
    • 默认限制往往不适合高并发。
  2. 内核 TCP 参数不适合大量连接

    • TIME_WAIT 过多
    • SYN 队列不足
    • 连接积压队列太小
    • 临时端口范围不足
  3. Nginx worker 配置不合理

    • worker 数量不足
    • worker_connections 太小
    • keepalive 配置不当
  4. 后端服务连接数不足

    • 应用线程池太小
    • 数据库连接池太小或太大
    • Redis / MySQL / PostgreSQL 达到最大连接数
  5. CPU、内存、磁盘 I/O、网络带宽瓶颈

    • CPU 负载高
    • 内存频繁 Swap
    • 磁盘 I/O 等待过高
    • 网卡带宽耗尽
  6. 缺少限流、缓存、负载均衡

    • 所有请求直接打到后端
    • 没有静态资源缓存
    • 没有 CDN 或本地缓存
    • 没有削峰策略

二、基础环境准备

首先更新 Debian 系统,并安装常用工具。

sudo apt update
sudo apt upgrade -y
sudo apt install -y vim curl wget net-tools htop iotop iftop lsof unzip git sysstat tcpdump nginx

查看系统版本:

cat /etc/debian_version

查看内核版本:

uname -a

查看 CPU 信息:

lscpu

查看内存信息:

free -h

查看磁盘空间:

df -h

查看磁盘 I/O:

iostat -x 1

如果系统没有 iostat 命令,可安装:

sudo apt install -y sysstat

查看当前网络连接情况:

ss -ant

统计当前连接数:

ss -ant | wc -l

统计各 TCP 状态数量:

ss -ant | awk 'NR>1 {print $1}' | sort | uniq -c | sort -nr

三、提升系统文件句柄限制

高并发场景下,文件句柄限制非常关键。Linux 系统中,每个 TCP 连接都会占用文件描述符。如果限制过低,可能出现如下错误:

Too many open files

查看当前限制:

ulimit -n

查看系统最大文件句柄数:

cat /proc/sys/fs/file-max

临时提升当前 Shell 文件句柄:

ulimit -n 1048576

但临时设置重启后会失效,需要修改配置文件。

编辑 /etc/security/limits.conf

sudo vim /etc/security/limits.conf

在文件末尾加入:

* soft nofile 1048576
* hard nofile 1048576
root soft nofile 1048576
root hard nofile 1048576

* soft nproc 1048576
* hard nproc 1048576
root soft nproc 1048576
root hard nproc 1048576

确保 PAM 加载 limits 配置:

sudo vim /etc/pam.d/common-session

确认存在以下内容,没有则添加:

session required pam_limits.so

同时编辑:

sudo vim /etc/pam.d/common-session-noninteractive

加入:

session required pam_limits.so

对于 systemd 管理的服务,还需要修改 systemd 默认限制。

编辑 /etc/systemd/system.conf

sudo vim /etc/systemd/system.conf

加入或修改:

DefaultLimitNOFILE=1048576
DefaultLimitNPROC=1048576

编辑 /etc/systemd/user.conf

sudo vim /etc/systemd/user.conf

加入或修改:

DefaultLimitNOFILE=1048576
DefaultLimitNPROC=1048576

重新加载 systemd:

sudo systemctl daemon-reexec

重启服务器:

sudo reboot

重启后验证:

ulimit -n

查看某个服务的文件句柄限制,例如 Nginx:

cat /proc/$(pidof nginx | awk '{print $1}')/limits

四、优化 Debian 内核参数

高并发连接依赖 Linux TCP/IP 栈。默认参数偏保守,在高并发场景下需要优化。

编辑内核参数配置文件:

sudo vim /etc/sysctl.conf

在文件末尾加入以下配置:

# ==============================
# Debian 高并发内核优化配置
# ==============================

# 系统最大打开文件数
fs.file-max = 2097152

# 单个进程可打开文件数
fs.nr_open = 2097152

# 允许更多的 TCP 半连接队列
net.ipv4.tcp_max_syn_backlog = 65535

# listen 队列最大长度
net.core.somaxconn = 65535

# 网卡接收队列最大长度
net.core.netdev_max_backlog = 65535

# 开启 SYN Cookie,防止 SYN Flood
net.ipv4.tcp_syncookies = 1

# TCP 连接重试次数,降低无效连接占用
net.ipv4.tcp_syn_retries = 3
net.ipv4.tcp_synack_retries = 3

# TCP FIN_WAIT2 状态超时时间
net.ipv4.tcp_fin_timeout = 15

# TCP keepalive 探测时间
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 5

# 允许本地端口范围扩大,适合大量短连接
net.ipv4.ip_local_port_range = 1024 65535

# TIME_WAIT 最大数量
net.ipv4.tcp_max_tw_buckets = 262144

# 开启 TCP Fast Open
net.ipv4.tcp_fastopen = 3

# TCP 接收缓冲区
net.ipv4.tcp_rmem = 4096 87380 67108864

# TCP 发送缓冲区
net.ipv4.tcp_wmem = 4096 65536 67108864

# Socket 接收缓冲区最大值
net.core.rmem_max = 67108864

# Socket 发送缓冲区最大值
net.core.wmem_max = 67108864

# Socket 默认接收缓冲区
net.core.rmem_default = 262144

# Socket 默认发送缓冲区
net.core.wmem_default = 262144

# 减少 TIME_WAIT 连接影响
net.ipv4.tcp_tw_reuse = 1

# 禁用反向路径过滤,某些负载均衡场景需要
net.ipv4.conf.all.rp_filter = 0
net.ipv4.conf.default.rp_filter = 0

# 避免低内存情况下频繁 OOM
vm.overcommit_memory = 1

# 降低 swap 使用倾向
vm.swappiness = 10

# 提高脏页刷盘阈值,适合一定写入压力场景
vm.dirty_ratio = 20
vm.dirty_background_ratio = 10

使配置立即生效:

sudo sysctl -p

查看是否生效:

sysctl net.core.somaxconn
sysctl net.ipv4.tcp_max_syn_backlog
sysctl net.ipv4.ip_local_port_range
sysctl fs.file-max

注意:
net.ipv4.tcp_tw_recycle 已在新内核中移除,不要再配置。
tcp_tw_reuse 可以减少 TIME_WAIT 对客户端短连接场景的影响,但并不是万能方案。生产环境中仍建议配合连接池、KeepAlive 和负载均衡使用。


五、Nginx 高并发优化

Nginx 是 Debian 服务器中最常见的高并发入口服务。它适合作为静态资源服务器、反向代理、HTTPS 网关和负载均衡器。

安装 Nginx:

sudo apt install -y nginx

查看 Nginx 版本和编译参数:

nginx -V

备份默认配置:

sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak

编辑 Nginx 主配置:

sudo vim /etc/nginx/nginx.conf

推荐配置如下:

user www-data;
worker_processes auto;
worker_rlimit_nofile 1048576;
pid /run/nginx.pid;

events {
    use epoll;
    worker_connections 65535;
    multi_accept on;
    accept_mutex off;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    types_hash_max_size 4096;
    server_tokens off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # 连接超时
    keepalive_timeout 30;
    keepalive_requests 10000;
    client_header_timeout 10;
    client_body_timeout 10;
    send_timeout 10;

    # 请求体大小
    client_max_body_size 50m;

    # 缓冲区
    client_body_buffer_size 128k;
    client_header_buffer_size 4k;
    large_client_header_buffers 4 16k;

    # 打开文件缓存
    open_file_cache max=200000 inactive=60s;
    open_file_cache_valid 60s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    # Gzip 压缩
    gzip on;
    gzip_comp_level 5;
    gzip_min_length 1k;
    gzip_buffers 16 8k;
    gzip_types
        text/plain
        text/css
        application/json
        application/javascript
        application/xml
        application/xml+rss
        text/javascript
        image/svg+xml;

    # 日志格式
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for" '
                    'rt=$request_time uct=$upstream_connect_time '
                    'uht=$upstream_header_time urt=$upstream_response_time';

    access_log /var/log/nginx/access.log main;
    error_log /var/log/nginx/error.log warn;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

测试配置:

sudo nginx -t

重启 Nginx:

sudo systemctl restart nginx

查看 Nginx 状态:

sudo systemctl status nginx

查看 Nginx 进程限制:

cat /proc/$(pgrep -o nginx)/limits

六、Nginx 反向代理优化

如果 Nginx 后面有应用服务,例如 Node.js、Java、Go、PHP-FPM,可以配置 upstream keepalive,减少频繁建立连接带来的开销。

创建站点配置:

sudo vim /etc/nginx/conf.d/api.conf

示例配置:

upstream backend_api {
    server 127.0.0.1:3000 max_fails=3 fail_timeout=30s;
    keepalive 256;
}

server {
    listen 80 reuseport;
    server_name example.com;

    access_log /var/log/nginx/api_access.log main;
    error_log /var/log/nginx/api_error.log warn;

    location / {
        proxy_pass http://backend_api;

        proxy_http_version 1.1;
        proxy_set_header Connection "";

        proxy_set_header Host $host;
        proxy_set_header Real-IP $remote_addr;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_connect_timeout 3s;
        proxy_send_timeout 10s;
        proxy_read_timeout 30s;

        proxy_buffering on;
        proxy_buffer_size 16k;
        proxy_buffers 16 16k;
        proxy_busy_buffers_size 64k;

        proxy_next_upstream error timeout http_502 http_503 http_504;
    }
}

测试并重载:

sudo nginx -t
sudo systemctl reload nginx

如果有多个后端实例,可以这样配置:

upstream backend_api {
    least_conn;
    server 127.0.0.1:3000 max_fails=3 fail_timeout=30s;
    server 127.0.0.1:3001 max_fails=3 fail_timeout=30s;
    server 127.0.0.1:3002 max_fails=3 fail_timeout=30s;
    server 127.0.0.1:3003 max_fails=3 fail_timeout=30s;
    keepalive 512;
}

启动多个后端服务后,Nginx 会自动进行负载均衡。least_conn 适合请求耗时不均匀的接口服务,默认轮询则适合每个请求耗时相对接近的业务。


七、启用 HTTPS 与 HTTP/2

高并发网站通常需要 HTTPS。Debian 上可以使用 Certbot 自动申请 Let’s Encrypt 证书。

安装 Certbot:

sudo apt install -y certbot python3-certbot-nginx

申请证书:

sudo certbot --nginx -d example.com -d www.example.com

测试自动续期:

sudo certbot renew --dry-run

查看定时任务:

systemctl list-timers | grep certbot

HTTPS 配置示例:

server {
    listen 443 ssl http2 reuseport;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    ssl_session_cache shared:SSL:50m;
    ssl_session_timeout 10m;
    ssl_session_tickets off;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    location / {
        proxy_pass http://backend_api;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

HTTP 跳转 HTTPS:

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

八、静态资源缓存优化

如果业务中包含大量图片、CSS、JS、字体文件,应该尽量让 Nginx 直接处理,并开启浏览器缓存。

示例配置:

server {
    listen 80 reuseport;
    server_name static.example.com;

    root /var/www/static;

    location ~* \.(jpg|jpeg|png|gif|ico|webp|svg|css|js|woff|woff2|ttf|eot)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
        access_log off;
    }

    location / {
        try_files $uri $uri/ =404;
    }
}

创建目录并设置权限:

sudo mkdir -p /var/www/static
sudo chown -R www-data:www-data /var/www/static

测试配置:

sudo nginx -t
sudo systemctl reload nginx

静态资源优化建议:

  1. 尽量使用 CDN。
  2. 静态资源文件名加入 hash。
  3. 开启 gzip 或 brotli。
  4. 图片使用 WebP 或 AVIF。
  5. 避免静态资源请求打到后端应用。

九、开启 Nginx 访问限流

高并发不等于无限制放行。面对恶意请求、爬虫、接口刷量,必须进行限流。

http 块中加入:

limit_req_zone $binary_remote_addr zone=req_limit_per_ip:20m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:20m;

在 server 或 location 中使用:

location /api/ {
    limit_req zone=req_limit_per_ip burst=20 nodelay;
    limit_conn conn_limit_per_ip 50;

    proxy_pass http://backend_api;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

配置说明:

  • rate=10r/s:每个 IP 每秒最多 10 个请求。
  • burst=20:允许短时间突发 20 个请求。
  • nodelay:突发请求不延迟,超过立即拒绝。
  • limit_conn:限制单个 IP 并发连接数。

重载 Nginx:

sudo nginx -t
sudo systemctl reload nginx

十、PHP-FPM 高并发优化

如果使用 PHP,应优化 PHP-FPM。

查看 PHP 版本:

php -v

编辑 PHP-FPM 池配置,例如 PHP 8.2:

sudo vim /etc/php/8.2/fpm/pool.d/www.conf

推荐配置:

pm = dynamic
pm.max_children = 200
pm.start_servers = 20
pm.min_spare_servers = 20
pm.max_spare_servers = 50
pm.max_requests = 5000

request_terminate_timeout = 30s
rlimit_files = 1048576

配置解释:

  • pm.max_children:最大 PHP 工作进程数。
  • pm.max_requests:每个进程处理一定请求后重启,防止内存泄漏。
  • request_terminate_timeout:防止慢请求长期占用进程。

重启 PHP-FPM:

sudo systemctl restart php8.2-fpm

查看状态:

sudo systemctl status php8.2-fpm

Nginx 连接 PHP-FPM 示例:

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php8.2-fpm.sock;

    fastcgi_connect_timeout 3s;
    fastcgi_send_timeout 10s;
    fastcgi_read_timeout 30s;

    fastcgi_buffer_size 32k;
    fastcgi_buffers 16 32k;
}

十一、数据库连接池与缓存优化

高并发系统中,数据库往往是最容易被打爆的组件。服务器系统参数和 Nginx 优化只能提升入口能力,如果数据库无法承载,最终仍会出现慢查询、连接耗尽和请求堆积。

1. MySQL / MariaDB 基础优化

安装 MariaDB:

sudo apt install -y mariadb-server

编辑配置:

sudo vim /etc/mysql/mariadb.conf.d/50-server.cnf

示例参数:

[mysqld]
max_connections = 1000
back_log = 1024
table_open_cache = 4096
thread_cache_size = 128

innodb_buffer_pool_size = 2G
innodb_log_file_size = 512M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT

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

重启数据库:

sudo systemctl restart mariadb

查看连接数:

sudo mysql -e "SHOW VARIABLES LIKE 'max_connections';"
sudo mysql -e "SHOW STATUS LIKE 'Threads_connected';"
sudo mysql -e "SHOW STATUS LIKE 'Max_used_connections';"

注意:
max_connections 不是越大越好。连接数过高会导致内存消耗暴涨。应用层应使用连接池,并设置合理的最大连接数。

2. Redis 缓存

安装 Redis:

sudo apt install -y redis-server

编辑配置:

sudo vim /etc/redis/redis.conf

推荐调整:

maxclients 10000
timeout 0
tcp-keepalive 300
supervised systemd

如果 Redis 作为缓存使用,可以配置内存上限和淘汰策略:

maxmemory 2gb
maxmemory-policy allkeys-lru

重启 Redis:

sudo systemctl restart redis-server

查看 Redis 状态:

redis-cli info clients
redis-cli info memory

十二、启用 Swap 但降低使用倾向

高并发场景中,内存不足会导致服务崩溃。可以配置 Swap 作为兜底,但不能依赖 Swap,因为 Swap 会明显降低性能。

创建 4G Swap:

sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

写入 /etc/fstab

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

设置 swappiness:

sudo sysctl vm.swappiness=10

永久生效:

echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf

查看 Swap:

free -h
swapon --show

十三、使用 systemd 管理应用服务

高并发生产环境中,不建议直接使用 nohup 启动后端服务,应使用 systemd 管理,确保异常退出后自动重启。

以 Node.js 应用为例,创建服务文件:

sudo vim /etc/systemd/system/api.service

写入:

[Unit]
Description=API Service
After=network.target

[Service]
Type=simple
User=www-data
WorkingDirectory=/var/www/api
ExecStart=/usr/bin/node /var/www/api/app.js
Restart=always
RestartSec=3

LimitNOFILE=1048576
LimitNPROC=1048576

Environment=NODE_ENV=production
Environment=PORT=3000

[Install]
WantedBy=multi-user.target

重新加载 systemd:

sudo systemctl daemon-reload

启动服务:

sudo systemctl enable api
sudo systemctl start api

查看状态:

sudo systemctl status api

查看日志:

journalctl -u api -f

如果是 Go 服务:

[Service]
ExecStart=/var/www/api/app

如果是 Java 服务:

[Service]
ExecStart=/usr/bin/java -Xms2g -Xmx2g -jar /var/www/api/app.jar

十四、防火墙与安全限制

高并发服务器也需要基础安全策略。Debian 可以使用 UFW 快速管理防火墙。

安装 UFW:

sudo apt install -y ufw

开放 SSH、HTTP、HTTPS:

sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

启用防火墙:

sudo ufw enable

查看状态:

sudo ufw status verbose

如果 SSH 端口不是 22,例如 2222:

sudo ufw allow 2222/tcp

限制某个端口只允许内网访问,例如 Redis:

sudo ufw allow from 10.0.0.0/8 to any port 6379 proto tcp

拒绝外部访问 Redis:

sudo ufw deny 6379/tcp

十五、日志与监控

高并发系统必须监控,否则无法判断瓶颈在哪里。

1. 查看系统负载

uptime
top
htop

2. 查看 CPU 使用率

mpstat 1

安装:

sudo apt install -y sysstat

3. 查看内存

free -h
vmstat 1

4. 查看磁盘 I/O

iostat -x 1

重点关注:

  • %util
  • await
  • r/s
  • w/s

5. 查看网络流量

iftop

如果未安装:

sudo apt install -y iftop

6. 查看连接数

ss -ant | wc -l

统计连接状态:

ss -ant | awk 'NR>1 {print $1}' | sort | uniq -c | sort -nr

查看某端口连接数,例如 80:

ss -ant | grep ':80' | wc -l

查看访问 IP 排名:

awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -20

查看耗时较高的请求:

awk '$NF > 1 {print}' /var/log/nginx/access.log | head

十六、压测验证

优化完成后,必须进行压测。可以使用 wrkabhey

安装 wrk:

sudo apt install -y build-essential git
cd /usr/local/src
sudo git clone https://github.com/wg/wrk.git
cd wrk
sudo make
sudo cp wrk /usr/local/bin/

压测示例:

wrk -t8 -c1000 -d60s http://example.com/

参数说明:

  • -t8:8 个线程
  • -c1000:1000 个并发连接
  • -d60s:持续 60 秒

测试 API:

wrk -t8 -c2000 -d60s --latency http://example.com/api/test

安装 ApacheBench:

sudo apt install -y apache2-utils

压测:

ab -n 100000 -c 1000 http://example.com/

压测时需要观察服务器状态:

htop
iostat -x 1
vmstat 1
ss -ant | awk 'NR>1 {print $1}' | sort | uniq -c | sort -nr

压测后重点关注:

  1. QPS 是否达到预期。
  2. 平均响应时间是否稳定。
  3. P95 / P99 延迟是否过高。
  4. 是否出现 502、503、504。
  5. CPU 是否打满。
  6. 内存是否持续上涨。
  7. 数据库连接数是否耗尽。
  8. TIME_WAIT 是否异常过多。

十七、一键应用系统优化脚本

下面提供一个 Debian 高并发基础优化脚本,可快速应用系统限制和内核参数。

创建脚本:

sudo vim /root/debian-high-concurrency-optimize.sh

写入以下内容:

#!/bin/bash

set -e

echo "开始 Debian 高并发基础优化..."

cat >> /etc/security/limits.conf <> /etc/pam.d/common-session
grep -q "pam_limits.so" /etc/pam.d/common-session-noninteractive || echo "session required pam_limits.so" >> /etc/pam.d/common-session-noninteractive

mkdir -p /etc/systemd/system.conf.d
cat > /etc/systemd/system.conf.d/limits.conf < /etc/systemd/user.conf.d/limits.conf < /etc/sysctl.d/99-high-concurrency.conf <

赋予执行权限:

sudo chmod +x /root/debian-high-concurrency-optimize.sh

执行脚本:

sudo bash /root/debian-high-concurrency-optimize.sh

重启服务器:

sudo reboot

重启后验证:

ulimit -n
sysctl net.core.somaxconn
sysctl net.ipv4.tcp_max_syn_backlog
sysctl fs.file-max

十八、高并发架构建议

系统参数优化只是基础,高并发真正稳定运行还需要架构配合。

建议采用以下方案:

  1. Nginx 作为统一入口

    • 处理 HTTPS
    • 反向代理
    • 限流
    • 静态资源缓存
  2. 应用服务多实例部署

    • 单机多进程
    • 多机负载均衡
    • 使用 systemd / Supervisor / Docker 管理
  3. 数据库连接池

    • 控制最大连接数
    • 避免无限制创建连接
    • 慢查询优化
  4. Redis 缓存热点数据

    • 降低数据库压力
    • 缓存接口结果
    • 使用合理过期时间
  5. 静态资源 CDN

    • 降低源站带宽压力
    • 提升访问速度
  6. 限流与熔断

    • 防止瞬时流量打穿系统
    • 对异常接口进行隔离
  7. 异步削峰

    • 使用消息队列处理非实时任务
    • 例如订单通知、邮件发送、日志入库
  8. 监控告警

    • CPU、内存、磁盘、网络
    • Nginx 状态
    • 应用接口耗时
    • 数据库慢查询
    • Redis 命中率

十九、常见故障排查

1. 出现 Too many open files

检查文件句柄:

ulimit -n
cat /proc/$(pgrep -o nginx)/limits

解决:

sudo systemctl daemon-reexec
sudo systemctl restart nginx

必要时重启服务器:

sudo reboot

2. Nginx 502 Bad Gateway

检查后端服务是否正常:

curl -I http://127.0.0.1:3000
sudo systemctl status api
journalctl -u api -f

检查 Nginx 错误日志:

tail -f /var/log/nginx/error.log

3. TIME_WAIT 过多

查看状态:

ss -ant | awk 'NR>1 {print $1}' | sort | uniq -c | sort -nr

优化方向:

  • 开启 upstream keepalive
  • 应用使用连接池
  • 避免频繁短连接
  • 适当调优 TCP 参数

4. CPU 很高

查看进程:

top
htop
ps aux --sort=-%cpu | head

检查 Nginx 访问量:

awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head

5. 内存持续上涨

查看内存:

free -h
ps aux --sort=-%mem | head

如果是应用内存泄漏,需要优化代码或设置服务自动重启策略。


二十、总结

Debian 高并发优化不能只改一个参数,也不能简单地把所有数值调到最大。正确的做法是从系统、内核、Nginx、应用、数据库、缓存、监控和架构多个层面综合处理。

一套较完整的 Debian 高并发解决方案应包括:

  • 提升文件句柄限制;
  • 优化 TCP 内核参数;
  • 调整 Nginx worker、连接数、keepalive、缓存和限流;
  • 使用 upstream keepalive 减少后端连接开销;
  • 使用 systemd 管理应用进程;
  • 合理配置 PHP-FPM、Node.js、Go 或 Java 服务;
  • 优化数据库连接数和慢查询;
  • 使用 Redis 缓存热点数据;
  • 配置 Swap 作为兜底;
  • 使用监控和压测持续验证效果;
  • 在业务层面引入限流、缓存、异步削峰和负载均衡。

如果是中小型业务,单台 Debian 服务器经过上述优化后,配合 Nginx、缓存和合理的应用架构,通常可以承载相当可观的并发请求。但如果业务流量继续增长,最终仍应走向多节点部署、负载均衡、数据库读写分离、缓存集群和分布式架构。高并发的本质不是单机参数调优,而是系统容量规划、资源隔离和架构治理的综合能力。

目录结构
全文