排查阿里云服务器宕机:磁盘告警背后的真正原因

December 1, 2025

背景

最近,我们部署在阿里云的生产服务意外宕机。最初的排查并不顺利。和许多云平台一样,基础监控虽然报了警,措辞却含糊,甚至可能把排查引向错误方向。

我收到的通知只说“磁盘使用率高”。乍看像是磁盘快满了,但实际问题远比剩余容量复杂。

真正出现的是 IOPS 饱和

监控没有清楚说明:服务器耗尽了 **IOPS(每秒输入输出操作数)**配额。云盘的 IOPS 达到上限,整台机器都可能像停住一样,连 SSH 和云管理控制台都访问不了。

在阿里云论坛上,不少人有类似经历:告警未指出具体指标,开发者很难确认根因。

为什么会发生?

云服务器通常共享底层存储资源。每台虚拟机的 IOPS 配额取决于规格和云盘类型。以下情况都可能突然制造大量读写:

  • 数据库查询遭遇内存紧张,开始使用交换空间。
  • 日志写入过于频繁。
  • 流量激增造成大量磁盘 I/O。
  • 备份、索引等后台任务。

一旦 IOPS 冲到上限,整个服务器都可能失去响应。

社区的经历

阿里云论坛上有人报告过类似问题:

"Aliyun普通云服务器IOPS突然跑满,服务器上只跑了一个小java,IOPS跑满之后服务器就宕机,无法登陆,通过阿里云管理后台也无法登陆。"

(上面是论坛原话。作者指出,当时服务器只运行一个很小的 Java 应用。)

其中一位用户找到了原因:

"主要是由于内存不够了,使用swap文件进行内存交换导致的~建议从内存入手,不要先排查io的问题"

(按这位用户的经验,首先要排查内存不足引发的交换。)

还有人描述了反复遇到的情况:

"很久没遇到磁盘IO过高的问题了,也知道这个是所有云服务器的硬伤... 今天下午五点左右收到报警RDS连接数过高网站打不开,阿里云后台看了一下是磁盘IO有点高导致,问题重启一下就好了"

(该用户的告警是 RDS 连接数过高,随后发现磁盘 I/O 偏高,重启后暂时恢复。)

这几条经验说明什么?

  1. 云平台的磁盘告警可能含糊:有时指 IOPS 饱和,并非容量不足。
  2. IOPS 是有配额的共享资源,上限由服务规格等因素决定。
  3. 内存压力经常间接造成 IOPS 问题,特别是系统开始大量交换时。
  4. 重启可以临时恢复,但根因仍在。
  5. 长期选项
    • 升级到更高 IOPS 的云盘或 SSD 存储。
    • 优化内存使用,减少交换。
    • 单独监控 IOPS,同时关注空间。
    • I/O 密集型应用可以考虑分布式存储。

诊断工具为什么选 atop?

服务器抖动和瞬时宕机的难点,是留下问题发生那一小段时间的证据。很多传统工具存在以下局限:

  • 30 或 60 秒采样一次,可能错过尖峰。
  • 进程级指标不够详细。
  • 事后无法回看当时发生了什么。

这时 atop 尤其有用。

atop 是什么?

atop 是开源的单机性能监控工具,具有以下特点:

  1. 保留历史:除实时显示外,还把详细指标写入磁盘,方便事后排查。

  2. 细粒度采样:可配置为一秒一次。

  3. 指标全面:有系统、进程及线程级数据,包括:

    • CPU(用户、系统、中断、I/O 等待)
    • 内存(RSS、交换、缺页)
    • 磁盘 I/O(读写字节数、IOPS)
    • 网络(安装 netatop 模块时)
    • 进程状态变化
  4. 开销较低:即便采集多种指标,其自身资源占用相对较小。

我为什么为这次排查选择 atop?

短暂问题可能几秒内出现又消失。atop 能按时间回放。把它作为后台服务并采用一秒采样,可以:

  1. 持续记录系统状态。
  2. 故障出现时记下准确时间。
  3. 回看那个时刻各个进程正在做什么。

一位有经验的工程师写道:

"抖动问题一般都是发生在一瞬间,可能下一秒就已经不存在了。那么对于这类问题要如何定位呢?首先还是要能收集到发生问题的瞬间,相关的系统信息。"

(上面这句话强调,定位瞬间抖动,需要先留住发生时的系统信息。)

安装和配置

在阿里云 Ubuntu 服务器上配置 atop 做细粒度监控:

# Update package list
sudo apt update

# Install atop
sudo apt install -y atop

# If you encounter dpkg configuration issues, run:
sudo dpkg --configure -a
apt install -y atop

# Check the default configuration
cat /etc/default/atop

默认的 /etc/default/atop 配置大致如下:

# /etc/default/atop
# see man atoprc for more possibilities to configure atop execution

LOGOPTS=""
LOGINTERVAL=5
LOGGENERATIONS=2
LOGPATH=/var/log/atop

我使用以下配置:

# Edit the configuration file
nano /etc/default/atop

# Configuration used:
# LOGINTERVAL=5    - Sample every 5 seconds (balance between granularity and storage)
# LOGGENERATIONS=2 - Keep logs for 2+2=4 days (saves disk space on system partition)
# LOGPATH=/var/log/atop - Default log location

📓 说明: LOGINTERVAL 决定指标采样间隔。我最后选了 5 秒,在捕获瞬态问题与控制日志空间之间折中。在重点时段可暂改为 1 秒,但日志会明显增大。

📓 说明: 这里的 LOGGENERATIONS=2 对应日志保留 LOGGENERATIONS + 2 = 4 days。系统盘空间有限时尤其要注意,请按可用空间和排查需要调整。

最后启用并启动 atop 服务:

# Enable atop to start on boot
systemctl enable atop

# Start the atop service immediately
systemctl start atop

# Verify it's running
systemctl status atop

用 atop 查问题

atop 运行后会在 /var/log/atop/ 保存日志。发生故障后可以回看当时的情况。

怎样查看已保存的日志?

基本命令: -r 后接日志路径。

# View historical data for a specific date
atop -r /var/log/atop/atop_20211021

查看当天日志: 省略文件名时,atop 会自动选择当天文件。

# Automatically opens today's log
atop -r

在日志中前后移动

打开日志后,可以按以下键在时间线上导航:

按键作用
t前往下一份快照。
T(Shift+t)返回上一份快照。
b跳到指定时间,按提示输入时间,如 HH:MM。

操作示例

  1. 打开日志:atop -r /var/log/atop/atop_20211021
  2. 按 b,输入故障时间,例如下午 5:23 输入 17:23。
  3. 用 t 和 T 前后查看附近的快照。

筛选并排序

查看历史日志时,可用下列按键切换排序和显示方式:

按键作用
C按 CPU 使用排序。
M按内存使用排序。
D按磁盘使用排序。
N有进程网络数据时按网络使用排序。
A自动按最繁忙资源排序。
g通用输出(默认视图)。
m / d切换到内存或磁盘详情。
y显示线程级信息。

排序键是大写,小写键选择视图或执行其他操作。见 atop 手册。

怎样理解 atop 输出?

阅读输出时,我特别关注:

上半部分的全局指标

  • DSK 行的 busy 列:busy = io_ms / per_cpu_ms。较高的值(如超过 70%)可能提示 I/O 瓶颈。
  • CPU 行的 wait 列:I/O 等待时间。
  • 内存与换页指标:关注系统是否持续换入换出。
  • CPL 行:把平均负载与 CPU 核心数比较。

下半部分的进程指标

  • RDDSK/WRDSK:各进程的实际读写字节数。
  • DSK 列:所列进程中该进程的相对 I/O 占比。
  • CPUNR:进程在哪个核心上运行,有助于发现 CPU 绑定问题。

配套工具 perf

需要比 atop 更细的代码级分析时,可用 perf 采集性能数据:

# Start lightweight sampling (99 samples/second to minimize overhead)
perf record -g -a -F 99

# View the time range of collected data
perf report --header-only

# Analyze a specific time window (in timestamp format)
perf report --time 428090,428091

atop 用于查看系统整体健康状况,perf 用于分析具体代码,两者结合很适合排障。

历史 CPU 使用与进程证据

2026 年 11 月 13 日,在讨论 Docker 日志和监控后补充。

历史 CPU 曲线能回答主机什么时候忙。要找出当时哪个进程导致负载,必须有同一时段的进程级采样。事后安装工具,无法还原没有采集过的指标。

问题应收集的证据
主机 CPU 何时忙?已保存的 sar 数据或云 CPU 指标。
当时哪些进程占资源?已保存的 atop 记录、事先捕获的 pidstat 输出,或已配置的云端进程采集。
现在发生什么?top、htop 或按间隔运行的 pidstat。

用 sar 回看主机历史,用 pidstat 采集新的进程样本

sar 读取 sysstat 收集的活动记录。安装软件包并不代表周期采集已启用。请检查发行版的 cron 或 systemd 配置,并确认按日期生成数据文件。Sysstat 项目

# Today's saved CPU records, if collection was already enabled
sar -u

# Example saved file; use the actual date and path on your host
sar -u -f /var/log/sysstat/sa13 -s 10:00:00 -e 13:00:00

# Report each CPU from today's saved records
sar -P ALL

有些发行版把每日文件存在 /var/log/sa/。请核对报告头部的日期,不能只凭 sa13 判断数据属于故障月份。sar 手册

pidstat 从运行时起对任务采样,无法从 sar 历史文件中恢复旧进程列表。短期采集可以这样做:

# Five samples at two-second intervals
pidstat -u -p ALL 2 5

# Save a bounded ten-minute capture with timestamps
pidstat -H -u -p ALL 5 120 > pidstat-cpu.txt

需要持续保留系统和进程回放时,可以沿用 atop 的录制设置。短于采样间隔的尖峰可能漏掉,提高频率也会增加存储和采集工作量。见 pidstat 手册、atop 手册。

阿里云能监控进程吗?

可以,但 ECS 的 CPU 曲线本身不是进程历史。在本文更新时的文档中,云监控的操作系统监控提供占用最高的五个进程指标;实例接入 ECS 洞察后,还能看到进程资源时间序列、PID、命令和运行时长等。云监控指标、ECS 洞察

先确认相关采集器已安装且有数据,再选故障时段。覆盖范围、采样周期、保留期随服务和配置而异,不能假定每台 ECS 都有完整进程数据或统一保留 30 天。前五名采样也不是完整进程审计。

遇到磁盘告警,要对齐时间对比容量、I/O、内存和交换。如果容器日志占满空间,可另读 Docker 日志管理指南。清掉文件本身不能解释 CPU 或换页异常。

排查过程

第一步:找到 kswapd0

装好 atop 后,我回看宕机时间段的记录,按 D 以磁盘使用排序。位居榜首的竟然是 kswapd0。

# Viewing the log at the time of the incident
atop -r /var/log/atop/atop_20211021

# Press 'b' and enter the time when server went down
# Press 'D' to sort by disk usage

kswapd0 消耗的磁盘 I/O 相当惊人,RDDSK 和 WRDSK 远超各应用进程。

第二步:了解 kswapd0

kswapd0 到底是什么?我查到了以下信息。

kswapd0 是 Linux 负责虚拟内存管理的内核线程,参与内存回收:

  • 将不活跃的“冷”页从 RAM 移往交换空间。
  • 系统内存紧张时释放物理内存。
  • 平衡整体内存使用。

⚠️ 注意: kswapd0 的 CPU 或磁盘占用升高是一种症状。它可能表明系统缺 RAM,正通过换页回收内存。

为什么 kswapd0 会推高 IOPS?

物理内存紧张时:

  1. 内核要为新的分配腾出空间。
  2. kswapd0 回收不活跃页面,其中一部分写到交换文件或分区。
  3. 大量换出以及之后的换入产生密集读写。
  4. 有 IOPS 配额的云盘可能很快达到吞吐操作数上限。
  5. 其他磁盘请求排在交换 I/O 后面,系统变得难以响应。

Ask Ubuntu 上有人这样解释:

“kswapd0 是管理虚拟内存的进程。机器上通常有 RAM、交换空间,以及硬盘或 SSD 上的 EXT4 文件系统。”

Server Fault 的讨论中也提到:

“使用交换空间时,若系统不停在 RAM 与 swap 之间搬页,便会抖动,kswapd0 的 CPU 使用甚至可能达到 100%。”

分清内核线程与伪装进程

📓 说明: 少数恶意程序(尤其挖矿程序)会借用 kswapd0 这个名字,可结合几项信息核对:

  • 用户 ID:通常应为 root,即 UID 0。
  • 内核线程特征:查看 ps aux | grep kswapd0,正常线程一般以带方括号的 [kswapd0] 显示。
  • 父进程 ID:通常应为 kthreadd(PID 2)。

我这里确实是内存压力很大时正常运行的内核线程。

第三步:确认内存压力

我检查了几项内存指标:

# Check overall memory and swap usage
free -m

# Check for swap activity in real-time
vmstat 1

# Review memory info
cat /proc/meminfo | grep -E 'MemTotal|MemFree|MemAvailable|SwapTotal|SwapFree'

结果印证了判断:

  • 物理内存使用率超过 95%。
  • 交换空间正在被使用。
  • vmstat 中的 si(换入)和 so(换出)明显升高。

第四步:从 atop 日志看内存去了哪里

既然 kswapd0 是管理换页的系统线程,我开始怀疑根因在内存。我重新打开 atop 日志,按 M 以内存使用排序。

下面是事故时的实际 atop 输出:

ATOP - 17 2025/11/19  08:23:18             -------                   10s elapsed
PRC | sys   2.78s | user  17.34s | #proc   378 | #trun      4 | #tslpi  1480 | #tslpu      1 | #tidle    67 | #zombie     0 | #exit    100 |
CPU | sys      52% | user     344% | irq      1% | idle      0% | wait      0% | steal     0% | guest     0% |            | curf 3.50GHz |
cpu | sys      13% | user      86% | irq      1% | idle      0% | cpu001 w  0% | steal     0% | guest     0% |            | curf 3.50GHz |
cpu | sys      12% | user      87% | irq      1% | idle      0% | cpu002 w  0% | steal     0% | guest     0% |            | curf 3.50GHz |
cpu | sys      15% | user      84% | irq      1% | idle      0% | cpu003 w  0% | steal     0% | guest     0% |            | curf 3.50GHz |
CPL | avg1   256.79 | avg5  358.68 | avg15  380.30 | csw    54794 | intr   43799 |
MEM | tot    15.0G | free  181.8M | avail 840.0M | cache   1.0G | dirty   1.6M | buff   51.6M | slab  356.6M | slrec 163.4M | pgtab 141.9M |
MEM | numnode    1 |              |              | topsz  1.3M | shmem 275.2M |              | udpsz  0.0M |              |              |
SWP | tot     8.0M | free    0.0M | swcac   0.0M | zswap   0.0M | zstor   0.0M |              |              | vmcom  26.8G | vmlim   7.5G |
PAG | scan   3519G | compact    0 | numamig    0 | pgout    403 | pgin   2833 | swin       0 | swout      8 |              |              |
PSI | cpusome  96% | memsome    0% | memfull  0% | iosome    0% | iofull    0% | cs 88/70/57 | ms  1/45/84 | mf  1/35/67 | is  2/45/81 |
DSK |         vdb | busy       2% | read      29 | write    40 | discrd    0 | KiB/w     5 | MBr/s  0.2 | MBw/s   0.0 | avio 0.17 ms |
DSK |         vda | busy       0% | read       0 | write   362 | discrd  362 | KiB/w     0 | tcpno  2.1 | tcprs   0   | udpie    0   |
NET | transport   | tcpi   17.34s | tcpo    362 | udpi     367 | udpo    362 | tcpao    0 | tcppo   0   | icmpi    0   | icmpo    0   |
NET | network     | ipi    13743 | ipo     367 | ipfrw  13381 | deliv   362 |              |             | erri     0   | erro     0   |
NET | eth0  ----  | pcki   22063 | pcko   8035 | sp   0 Mbps | si 1639 Kbps | so 1639 Kbps | erri     0   | erro     0   | drpo     0   |
NET | veth691 --- | pcki    7738 | pcko   5255 | sp   0 Mbps | si 1564 Kbps | so   43 Mbps | erri     0   | erro     0   | drpo     0   |
NET | docker0 --- | pcki    7748 | pcko   5263 | sp   0 Mbps | si 1391 Kbps | so   43 Mbps | erri     0   | erro     0   | drpo     0   |

  PID     TID MINFLT MAJFLT VSTEXT VSLIBS VDATA VSTACK LOCKSZ VSIZE RSIZE   PSIZE  VGROW  RGROW SWAPSZ  RUID      EUID       MEM CMD      1/18
982148      -      7      0  28.5M  12.3M 482.0M 140.0K   0.0K 105.0G 389.7M   0B     0B    -0.9M    0B  root      root        3% node
912181      -      0      0 316.0K  45.2M 125.8M 132.0K   0.0K 433.4M 244.3M   0B     0B         0B    0B  www-data www-data    2% apache2
925653      -     46      0 316.0K  45.2M 125.5M 132.0K   0.0K 433.1M 242.0M   0B     0B     2.8M    0B  www-data www-data    2% apache2
881555      -     36      0 316.0K  45.2M 125.1M 132.0K   0.0K 432.7M 241.5M   0B     0B     2.1M    0B  www-data www-data    2% apache2
879139      -     45      0 316.0K  45.2M 125.7M 132.0K   0.0K 433.3M 241.5M   0B     0B     2.6M    0B  www-data www-data    2% apache2
929837      -     46      0 316.0K  45.2M 125.0M 132.0K   0.0K 432.6M 240.1M   0B     0B     2.6M    0B  www-data www-data    2% apache2
959057      -     46      0 316.0K  45.2M 125.1M 132.0K   0.0K 432.7M 239.3M   0B     0B     2.6M    0B  www-data www-data    2% apache2
959055      -     46      0 316.0K  45.2M 124.9M 132.0K   0.0K 432.5M 239.0M   0B     0B     2.6M    0B  www-data www-data    1% apache2
959058      -     88      0 316.0K  45.2M 124.7M 132.0K   0.0K 432.3M 238.9M   0B     0B     2.2M    0B  www-data www-data    1% apache2
980646      -   3946      0 316.0K  45.2M 122.9M 132.0K   0.0K 430.5M 228.5M   0B  16.2M    15.4M    0B  www-data www-data    1% apache2
980561      -   1540      0 316.0K  45.2M 122.9M 132.0K   0.0K 430.4M 228.4M   0B   6.0M     6.1M    0B  www-data www-data    1% apache2
980519      -   2522      0 316.0K  45.2M 122.9M 132.0K   0.0K 430.4M 228.4M   0B  18.2M     9.9M    0B  www-data www-data    1% apache2
980531      -   1858      0 316.0K  45.2M 122.9M 132.0K   0.0K 430.4M 228.3M   0B   8.0M     7.4M    0B  www-data www-data    1% apache2
980569      -   1367      0 316.0K  45.2M 122.9M 132.0K   0.0K 430.4M 228.3M   0B   6.0M     5.2M    0B  www-data www-data    1% apache2
980560      -     40      0 316.0K  45.2M 122.9M 132.0K   0.0K 430.4M 228.3M   0B   0B       0B      0B  www-data www-data    1% apache2
980659      -   1713      0 316.0K  45.2M 122.9M 132.0K   0.0K 430.5M 228.2M   0B  14.2M    15.5M    0B  www-data www-data    1% apache2
980605      -   3395      0 316.0K  45.2M 122.9M 132.0K   0.0K 430.4M 228.2M   0B  14.2M    14.2M    0B  www-data www-data    1% apache2
980438      -     23      0 316.0K  45.2M 122.9M 132.0K   0.0K 430.4M 228.2M   0B   0B      13.1M    0B  www-data www-data    1% apache2

日志中的关键现象

  1. CPU 平均负载异常高:CPL | avg1 256.79 | avg5 358.68 | avg15 380.30

    • 四核系统的平均负载达到 256,正常参考值通常在 4 以下。
    • 表明资源争用极其严重。
  2. 交换空间耗尽:SWP | tot 8.0M | free 0.0M

    • 交换空间已满,可用字节数为零。
    • 仅 10 秒就有 swout: 8 的换出活动。
  3. 内存压力:MEM | tot 15.0G | free 181.8M | avail 840.0M

    • 15 GB 中只剩 181 MB 空闲,按这个口径占用率约 98.8%。
    • 可用内存非常少。
  4. 大量页面扫描:PAG | scan 3519G

    • 内核扫描了约 3.5 TB 的页面,试图回收内存。
    • 这正是 kswapd0 大量工作的表现。

我又在内存视图(按 m)检查进程列表:

  • 多个 apache2 进程,各占用约 1%–2% 的内存。
  • 每个 apache2 进程的常驻大小(RSIZE)约为 225–240 MB。
  • 顶部还有一个 node 进程,占 3%(389.7 MB)。
  • 系统共有 378 个进程,空闲内存很少,持续换页。
# In atop, press 'M' to sort by memory
# Key columns to watch:
# - RSIZE: Resident memory (actual RAM used)
# - VSIZE: Virtual memory size
# - SWAPSZ: Amount of memory swapped to disk

第五步:追到 WordPress 容器

已经能看到 apache2 在耗内存,但要确认:这些进程是否来自运行 WordPress 的 Docker 容器?

首先查看 apache2 进程的 cgroup,判断其是否运行在容器内:

# Pick one of the apache2 PIDs and check its cgroup
ps -ef | grep apache2 | head -5
# Output showed:
# www-data 982148 912181  0 01:29 ?   00:00:10 apache2 -DFOREGROUND
# www-data 982156 912181  0 01:29 ?   00:00:11 apache2 -DFOREGROUND
# ...

# Check the parent process cgroup (all children have the same parent: 912181)
cat /proc/912181/cgroup

结果

0::/system.slice/docker-abc123def456789012345678901234567890abcdef1234567890abcdef12345678.scope

cgroup 路径含 docker-abc123def456...,说明该进程来自 ID 以 abc123def456 开头的 Docker 容器。

接着列出所有运行中的容器:

docker ps

输出中的发现

CONTAINER ID   IMAGE              COMMAND                  CREATED        STATUS        PORTS
abc123def456   wordpress:6.7.1    "docker-entrypoint.s…"   18 hours ago   Up 18 hours   80/tcp   my-site-wordpress-1
def789abc123   wordpress:6.7.1    "docker-entrypoint.s…"   18 hours ago   Up 18 hours   80/tcp   my-other-site-wordpress-1

找到了:abc123def456 正好对应名为 my-site-wordpress-1 的 WordPress 6.7.1 容器。

另一个办法:用 pstree 追踪进程树

pstree 可以直观展示父子关系:

pstree -p | grep apache2

输出

|-containerd-shim(912159)-+-apache2(912181)-+-apache2(982148)
|                         |                 |-apache2(982156)
|                         |                 |-apache2(982157)
|                         |                 |-apache2(982158)
|                         |                 |-apache2(982159)
|                         |                 |-apache2(982160)
|                         |                 |-apache2(982161)
|                         |                 |-apache2(982162)
|                         |                 |-apache2(982175)
|                         |                 `-apache2(983201)
|-containerd-shim(925630)-+-apache2(925653)-+-apache2(983301)
|                         |                 |-apache2(983415)
|                         |                 |-apache2(983528)
|                         |                 |-apache2(983642)
|                         |                 |-apache2(983755)
|                         |                 |-apache2(983869)
|                         |                 |-apache2(983870)
|                         |                 |-apache2(983982)
|                         |                 |-apache2(984095)
|                         |                 `-apache2(984096)

可以清楚看到:

  • 两个不同的 containerd-shim 父进程,PID 为 912159 和 925630。
  • 它们分别启动 apache2 主进程,PID 为 912181 和 925653。
  • 每个主进程又派生了十多个 apache2 工作子进程。
  • 两个容器共有二十多个 apache2 进程。

其他核对方式

# Method 1: Check processes inside a specific container
docker top abc123def456

# Method 2: Inspect container resource usage
docker stats abc123def456 def789abc123

# Method 3: Check container logs for apache2 activity
docker logs --tail 50 abc123def456

# Method 4: Enter the container and verify it's WordPress
docker exec -it abc123def456 ls -la /var/www/html/
# Should show: wp-config.php, wp-content, wp-includes, etc.

还有几条线索支持 WordPress 这一判断

  1. 进程命令:apache2 -DFOREGROUND

    • 标准 WordPress Docker 镜像以前台模式运行 Apache。
  2. 进程所有者:工作进程由 www-data 运行。

    • 这是 WordPress 容器中 PHP/Apache 常用的默认用户。
  3. 多个容器:实际上运行了两个 WordPress 容器:

    • my-site-wordpress-1(容器 abc123def456)
    • my-other-site-wordpress-1(容器 def789abc123)
    • 两者都在争用内存。
  4. 网络证据:atop 日志显示 Docker 网络:

    • docker0 网桥。
    • 多对 veth* 虚拟以太网接口。
    • 每个 WordPress 容器各有虚拟网络接口。

此时根因清楚了。 两个 WordPress 容器在流量或配置的作用下,各自产生许多 apache2 子进程,合计耗尽 15 GB RAM,促使系统频繁交换,随即耗尽 IOPS,服务器失去响应。

WordPress 为什么会启动这么多 Apache 进程?

Apache 进程多、内存高通常与流量或配置有关,严重时会影响整机稳定性。Server Fault 的讨论从 WordPress 运行 PHP 的方式解释:

“许多主机通过 Apache 的 mod_php 解析 PHP。默认 PHP 安装往往不是线程安全版本,这实际上要求 Apache 使用非线程型多处理模块,例如 prefork。这个模式让一个进程处理一个请求。”

意味着:

  1. WordPress 配合 Apache 的 mod_php:PHP 随 Apache 进程加载。
  2. 当 PHP 构建不具备线程安全性时,需要 prefork MPM,而非 worker/event。
  3. prefork 用独立进程处理并发请求,线程型 MPM 则可以使用较轻的线程。
  4. 现代浏览器会并发请求。一次页面加载可能同时请求十余份 CSS、JS、图片或 AJAX 数据。
  5. 再乘以访问量,不很大的流量也能带来数十个工作进程。

在我的环境中:

  • 有两个 WordPress 容器。
  • 每个容器使用默认 MaxRequestWorkers: 150。
  • 有负载时,每个容器启动 10–20 个活跃的 apache2 进程。
  • 粗算 20 个进程 × 240 MB,光 Apache 工作进程就有 4.8 GB 的常驻大小之和。
  • 加上约 389 MB 的 Node 和其他服务,15 GB 主机最终超过承载能力。

连锁反应:内存 → 换页 → IOPS → 宕机

事件经过如下:

  1. Apache2 占用 RAM:多个处理流量的进程逐步消耗可用物理内存。
  2. 内核开始换页:内存利用率约 95% 时,kswapd0 将不活跃页移入交换区。
  3. 交换抖动:反复读写交换区,使磁盘 I/O 飙升。
  4. IOPS 饱和:基础云盘的 IOPS 配额很快被耗尽。
  5. 系统无响应:包括正常业务在内的磁盘请求都开始排队,机器看起来像是“宕机”。
  6. 告警含糊:监控只说磁盘使用率高,没有指出内存耗尽导致的交换抖动。

解决办法

弄清根因后,我需要避免复发。下面是考虑和采用的办法。

方案一:调整 Apache,限制工作进程数

WordPress Docker 容器使用 Apache 的 prefork MPM,它可能启动过多工作进程。调整配置可限制内存占用。

第一步:以 root 进入容器

⚠️ 注意: 使用 -u 0 以 root 身份进入;默认 www-data 用户不能改配置。

# Enter the WordPress container as root (UID 0)
docker exec -u 0 -it abc123def456 /bin/bash

# Without -u 0, you'd be www-data and get "Permission denied" when editing configs

第二步:找到并编辑 Apache MPM 配置

# Find the Apache configuration directory
cd /etc/apache2/

# Check which MPM is being used
apache2 -V | grep -i mpm
# Output: Server MPM: prefork

# Edit the prefork MPM configuration
nano mods-available/mpm_prefork.conf

第三步:调整 prefork 参数

内存较少时,默认配置过于激进:

<IfModule mpm_prefork_module>
    StartServers             5
    MinSpareServers          5
    MaxSpareServers         10
    MaxRequestWorkers      150    # Too high! Can spawn 150 processes!
    MaxConnectionsPerChild   0
</IfModule>

针对内存受限环境的配置:

<IfModule mpm_prefork_module>
    StartServers             2
    MinSpareServers          2
    MaxSpareServers          5
    MaxRequestWorkers       20    # Limit to 20 workers max
    MaxConnectionsPerChild 1000   # Recycle workers after 1000 requests
</IfModule>

参数说明

  • StartServers:启动时创建的子进程数,从 5 减为 2。
  • MaxRequestWorkers:可同时处理的请求数上限,从 150 降为 20。
  • MaxConnectionsPerChild:定期回收工作进程以减轻内存泄漏的影响,从 0(不限制)改为 1000。

估算 MaxRequestWorkers

Available Memory for Apache = (Total RAM - OS overhead - other apps) / 2
                            = (15GB - 2GB - 3GB) / 2
                            = 5GB

Memory per Apache worker ≈ 240MB (from atop observations)

Safe MaxRequestWorkers = 5GB / 240MB ≈ 20 workers

第四步:应用更改

# Test the configuration for syntax errors
apache2ctl configtest

# If OK, reload Apache (inside container)
apache2ctl graceful

# Or restart from outside the container
docker restart abc123def456

第四步补充:其他可选优化

除 MPM 设置外,也可以考虑:

关闭或调整 KeepAlive

# Edit the main Apache config
nano /etc/apache2/apache2.conf

# Option 1: Disable KeepAlive for high-traffic sites
KeepAlive Off

# Option 2: Keep it on but reduce timeout
KeepAlive On
KeepAliveTimeout 2    # Reduced from default 5 seconds
MaxKeepAliveRequests 50

📓 说明: KeepAlive 允许在同一 TCP 连接上发送多个请求,有助于降低延迟。但在 prefork 中,等待后续请求时可能占住进程。高流量且内存较少的站点可以缩短超时或关闭它。

停用未使用的 Apache 模块

# List enabled modules
apache2ctl -M

# Disable unnecessary modules (examples)
a2dismod status
a2dismod autoindex
a2dismod negotiation

# Be careful not to disable essential modules like:
# - mpm_prefork (or your chosen MPM)
# - php7.x (needed for WordPress)
# - rewrite (needed for permalinks)

按原文的估算,每停用一个模块,每个 Apache 进程可少用约 1–5 MB;如果有二十多个进程,合计就比较可观。

第五步:持久化修改

直接在容器内部编辑,重建时会丢失。要持久化,可以:

# Create a custom Apache config file on the host
cat > /path/to/docker/volumes/apache-mpm-prefork.conf <<'EOF'
<IfModule mpm_prefork_module>
    StartServers             2
    MinSpareServers          2
    MaxSpareServers          5
    MaxRequestWorkers       20
    MaxConnectionsPerChild 1000
</IfModule>
EOF

# Mount it into the container via docker-compose.yml
# Add to your WordPress service:
volumes:
  - /path/to/docker/volumes/apache-mpm-prefork.conf:/etc/apache2/mods-available/mpm_prefork.conf:ro

或者自定义 Dockerfile:

FROM wordpress:6.7.1

# Copy optimized Apache config
COPY apache-mpm-prefork.conf /etc/apache2/mods-available/mpm_prefork.conf

另一条路:event MPM 配合 PHP-FPM

调整 prefork 可以缓解问题,但它按并发请求占用独立进程,内存效率有限。更现代的一种组合是 event MPM 配合 PHP-FPM。

好处

  • event MPM 使用线程,内存开销较低。
  • PHP-FPM 单独处理 PHP,Apache 能高效提供静态文件。
  • 资源隔离更好,PHP 崩溃不直接带走 Apache。
  • PHP 进程可细调,能单独限制 PHP 工作进程数。

取舍

  • ⚠️ 配置较复杂,需要重新配置 WordPress 容器。
  • ⚠️ 兼容性需验证,部分 WordPress 插件可能和 PHP-FPM 配合不佳。
  • ⚠️ 难以立即生效,需重新构建部署。

💡 提示: 如果经常遇到内存问题,又有时间做长期调整,可以评估迁移方案。要先恢复稳定,则可以从上面的 prefork 调整开始。

基础配置示例

FROM php:8.1-fpm

# Install Apache with event MPM
RUN apt-get update && apt-get install -y apache2
RUN a2dismod mpm_prefork && a2enmod mpm_event proxy_fcgi

# Configure Apache to proxy PHP requests to PHP-FPM
# (detailed setup omitted - requires significant configuration)

再考虑 PHP 脚本本身

根因有时是非常耗资源的 PHP 代码。若特定 WordPress 页面引起高内存:

定位有问题的脚本

# Monitor which PHP-FPM/Apache processes consume most memory
htop  # Press F4, search for "php" or "apache"

# Check WordPress error logs
docker exec abc123def456 tail -f /var/log/apache2/error.log

# Enable WordPress debug mode to identify slow queries
# Add to wp-config.php:
# define('WP_DEBUG', true);
# define('WP_DEBUG_LOG', true);

常见的 WordPress 性能问题

  • 低效查询:例如插件发起 N+1 查询。
  • 图片未优化:直接加载未经压缩的大图。
  • 插件过多:每个启用的插件都增加内存开销。
  • 缺少缓存:没有使用 Redis 或 Memcached 缓存对象。
  • 没有 CDN:静态资源全部经 Apache 提供。

📓 说明: PHP 优化超出本文范围,但如果只调 Apache 仍有内存问题,值得继续排查。

方案二:限制 Docker 容器资源(我最终的选择)

我用 Dokploy 管理容器,因此找到了更直接的办法:在 docker-compose.yml 中写入资源限制。限制在容器层强制执行,避免一个容器吃掉整台主机的资源。

我选择它的原因

  • 不用反复进入容器修改配置。
  • 由 Docker 执行限制。
  • 重新创建容器后仍保留。
  • 降低主机发生 OOM 的风险。
  • 可以融入现有 Dokploy 部署流程。

加入限制的 docker-compose.yml

version: "3.8"
services:
  wordpress:
    image: wordpress:6.7.1
    environment:
      WORDPRESS_DB_HOST: db
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: ${DB_PASSWORD}
      WORDPRESS_DB_NAME: wordpress
    volumes:
      - wordpress_data:/var/www/html
    restart: unless-stopped
    user: 33:33  # www-data user:group in the container

    # 🚀 RESOURCE LIMITS ADDED HERE
    deploy:
      resources:
        limits:
          # Set a hard memory limit to prevent the container from consuming all host RAM
          memory: 1G
          # Set a CPU limit (e.g., 50% of one core)
          cpus: '0.50'
        reservations:
          # Guarantee a minimum amount of memory for stability
          memory: 256M

volumes:
  wordpress_data:

资源参数说明

指令值含义
limits: memory1G容器的内存上限。若流量激增使 WordPress 超限,容器可能被 OOM 终止,并依据重启策略恢复,从而保护主机。
limits: cpus'0.50'平均最多使用单个 CPU 核心的 50%,避免一个容器独占主机 CPU。
reservations: memory256M服务的内存预留值。内存紧张时,平台会尽量为它维持这部分资源。

怎样计算适合自己环境的限额?

以一台 15 GB RAM、运行两个 WordPress 容器的服务器为例:

Total RAM: 15GB
OS + System Services: ~2GB
Other containers (dokploy, postgres, redis, etc.): ~3GB
Available for WordPress containers: 15GB - 2GB - 3GB = 10GB

For 2 WordPress containers:
Memory limit per container = 10GB / 2 = 5GB (conservative)
Or be more aggressive: 3GB per container (recommended)

CPU limit:
With 4 cores available, allocate 0.5-1.0 CPU per container

我的配置

deploy:
  resources:
    limits:
      memory: 3G      # Allow up to 3GB per WordPress container
      cpus: '1.0'     # Allow up to 1 full CPU core
    reservations:
      memory: 512M    # Guarantee at least 512MB

实际收益

  1. 资源隔离:一个容器不能再挤占另一个的全部资源。
  2. 占用可预测:每个容器 3 GB,两个最多 6 GB,剩余 9 GB 供系统和其他服务使用。
  3. 自动恢复:容器超过限额时可按策略重启,降低拖垮主机的风险。
  4. 配置不会漂移:资源限制保存在受版本控制的 docker-compose.yml 中。
  5. 适配 Dokploy:在界面中修改 Compose 文件并重新部署即可。

在 Dokploy 中应用

  1. 打开 WordPress 应用。
  2. 在配置标签页编辑 docker-compose.yml。
  3. 添加含资源限制的 deploy 段。
  4. 点击 Redeploy 重新部署。
  5. 用 docker stats 确认限额生效。
# Verify resource limits are applied
docker stats abc123def456 def789abc123

# Output shows the memory limit:
# CONTAINER ID   NAME              MEM USAGE / LIMIT   MEM %
# abc123def456   wordpress-1       450MiB / 3GiB       14.6%
# def789abc123   wordpress-2       520MiB / 3GiB       16.9%

结果: 限额实施后,内存使用趋于稳定,交换活动降至零,IOPS 饱和问题得到解决。此后在本文观察期内,服务器运行平稳,没有再次宕机。

参考资料

  1. 一毛钱关系. (2016, December 5). 阿里云服务器IOPS突然跑满,服务器宕机 [Forum post]. Retrieved December 1, 2025, from https://developer.aliyun.com/ask/201990

  2. baker668. (2015, February 9). 关于阿里云磁盘不定期出现IO过高的问题 [Forum post]. Retrieved December 1, 2025, from https://developer.aliyun.com/ask/184548

  3. 程序猿Ricky的日常干货. (2021, July 15). 使用atop和perf分析抖动问题的方法 [Blog post]. CSDN. Retrieved December 1, 2025, from https://blog.csdn.net/rikeyone/article/details/118756581

  4. 字节跳动技术团队. (2021, December 17). 深入字节版atop: 线上系统的性能监控实践 [Blog post]. 头条号. Retrieved December 1, 2025, from https://www.toutiao.com/article/7042577697628783141/

  5. Braiam. [@Braiam]. (2013, February 22). The process kswapd0 is the process that manages virtual memory. Your machine should have RAM, SWAP, and the EXT4 on your HDD/SSD. [Answer]. Ask Ubuntu. https://askubuntu.com/questions/259739/kswapd0-is-taking-a-lot-of-cpu

  6. LnxSlck. (2023, February 10). Kswapd0 process is using an incredibly high amount of CPU usage [Forum post]. LinuxQuestions.org. Retrieved December 1, 2025, from https://www.linuxquestions.org/questions/linux-security-4/kswapd0-process-is-using-an-incredibly-high-amount-of-cpu-usage-4175721879/

  7. Michael Hampton. [@Michael Hampton]. (2015, June 2). Kswapd0 may use 100% CPU when swap is in use because it's continuously trying to move pages between RAM and swap, creating a thrashing situation. [Answer]. Server Fault. https://serverfault.com/questions/696156/kswapd-often-uses-100-cpu-when-swap-is-in-use

  8. Daniel Ferradal. [@Daniel Ferradal]. (2016, December 29). Shamely, most hosting solutions out there people use, decide to parse php content through Apache with mod_php. Your PHP installation by default will surely not be thread-safe, this effectively forces Apache to use a non-threading mpm (multi-process module). Your Apache installation uses prefork (as you can see in the apachectl -V output). This mpm spawns a process per request. So if you are under a bit of load and nowadays knowing how many concurrent requests some browsers send, that list of process is quite usual. [Answer]. Server Fault. https://serverfault.com/questions/823121/why-is-apache-spawning-so-many-processes

  9. Godard, S. (n.d.). Sysstat: System performance tools for Linux. GitHub. Retrieved November 13, 2026.

  10. Godard, S. (n.d.). sar manual. Sysstat. Retrieved November 13, 2026.

  11. Godard, S. (n.d.). pidstat manual. Sysstat. Retrieved November 13, 2026.

  12. Atop project. (n.d.). atop manual. Retrieved November 13, 2026.

  13. 阿里云. (n.d.). 基础监控和操作系统监控. 云监控文档. Retrieved November 13, 2026.

  14. 阿里云. (n.d.). 洞察. ECS 洞察文档. Retrieved November 13, 2026.

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-12-01). 排查阿里云服务器宕机:磁盘告警背后的真正原因. https://caiborui.com/blog/2025-12-01-en-troubleshooting-aliyun-server-downtime-iops-zhtrans

@misc{borui2025-a07ddf54,
  author = {borui},
  title = {{排查阿里云服务器宕机:磁盘告警背后的真正原因}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-12-01-en-troubleshooting-aliyun-server-downtime-iops-zhtrans}
}