Background
Recently, I encountered a critical issue with our production services hosted on Aliyun (Alibaba Cloud). The server went down unexpectedly, and the initial investigation led me down a frustrating path. Like many cloud providers, Aliyun's basic monitoring system provided warnings, but they were surprisingly obscure and potentially misleading.
The alert I received simply warned about "high disk usage." This seemed straightforward at first - perhaps we were running out of storage space. However, the reality was far more complex and nuanced than a simple disk space issue.
The Real Problem: IOPS Saturation
What the monitoring system failed to clearly indicate was that the server was experiencing IOPS (Input/Output Operations Per Second) saturation, not a disk space problem. When IOPS reaches its limit on cloud servers, the entire system can grind to a halt, making the server completely unresponsive - you can't even SSH into it or access it through the cloud provider's management console.
This is a common pain point that many Aliyun users face, as evidenced by numerous forum discussions where developers encounter the same issue but struggle to identify the root cause due to unclear monitoring alerts.
Why This Happens
Cloud servers, unlike dedicated physical servers, share underlying storage resources. Each virtual machine is allocated a specific IOPS quota based on its tier and disk type. When your application suddenly generates excessive read/write operations - whether from:
- Database queries hitting swap due to memory constraints
- Log files being written too aggressively
- Sudden traffic spikes causing heavy disk I/O
- Background processes (backups, indexing, etc.)
...your IOPS can spike and max out, causing the entire server to become unresponsive.
Community Experiences
Many developers have reported similar issues in Aliyun forums:
"Aliyun普通云服务器IOPS突然跑满,服务器上只跑了一个小java,IOPS跑满之后服务器就宕机,无法登陆,通过阿里云管理后台也无法登陆。"
(Translation: Aliyun ordinary cloud server IOPS suddenly maxed out. The server only ran a small Java application, but after IOPS maxed out, the server crashed and became inaccessible, even through Aliyun's management console.)
One user discovered the root cause:
"主要是由于内存不够了,使用swap文件进行内存交换导致的~建议从内存入手,不要先排查io的问题"
(Translation: It's mainly because there isn't enough memory. Using swap files for memory exchange caused this. I suggest starting with memory investigation, don't troubleshoot I/O first.)
Another user described their recurring issue:
"很久没遇到磁盘IO过高的问题了,也知道这个是所有云服务器的硬伤... 今天下午五点左右收到报警RDS连接数过高网站打不开,阿里云后台看了一下是磁盘IO有点高导致,问题重启一下就好了"
(Translation: Haven't encountered high disk I/O issues in a while, but I know this is a common weakness of all cloud servers... Around 5 PM today, I received an alert about high RDS connections and the website was down. Checking Aliyun's backend showed high disk I/O was the cause. A restart fixed it.)
Key Takeaways
- Disk usage warnings on cloud platforms can be misleading - they might indicate IOPS saturation rather than storage capacity issues
- IOPS is a shared resource on cloud platforms and has hard limits based on your service tier
- Memory pressure often triggers IOPS problems when the system starts heavily using swap
- Quick fix: restart - but this doesn't solve the underlying cause
- Long-term solutions:
- Upgrade to higher IOPS tiers or SSD-based storage
- Optimize memory usage to avoid swap
- Monitor IOPS metrics specifically, not just disk space
- Consider distributed storage solutions for I/O-intensive applications
Choosing the Right Diagnostic Tool: Why atop?
When facing transient performance issues like server stuttering or momentary downtime, the biggest challenge is capturing what happened during that brief window. Most traditional monitoring tools either:
- Sample at intervals too long (30s, 60s) to catch the spike
- Don't provide detailed enough metrics at the process level
- Can't retroactively show what happened after the fact
This is where atop becomes invaluable.
What is atop?
atop is an open-source, single-machine performance monitoring tool that excels in several areas:
-
Historical logging: Unlike most real-time monitors, atop records detailed system metrics to disk, allowing you to investigate issues after they occur
-
Granular sampling: Can be configured to sample as frequently as every 1 second
-
Comprehensive metrics: Provides both system-wide and per-process/per-thread metrics including:
- CPU (user, system, IRQ, wait)
- Memory (RSS, swap, page faults)
- Disk I/O (read/write bytes, IOPS)
- Network (if netatop module is installed)
- Process state transitions
-
Low overhead: Despite collecting extensive metrics, atop's resource footprint is minimal
Why I Chose atop for This Investigation
For transient issues that occur and disappear within seconds, atop offers a critical advantage: time-travel debugging. By running atop as a background service with 1-second sampling intervals, I could:
- Let it continuously record system state
- When the issue occurred, check the exact timestamp
- Retroactively examine what every process was doing at that moment
As one experienced engineer noted:
"抖动问题一般都是发生在一瞬间,可能下一秒就已经不存在了。那么对于这类问题要如何定位呢?首先还是要能收集到发生问题的瞬间,相关的系统信息。"
(Translation: Jitter issues usually occur in an instant and may disappear the next second. So how do we locate such problems? First, we need to collect system information at the moment the problem occurs.)
Installation and Configuration
Setting up atop for fine-grained monitoring on my Aliyun Ubuntu server:
# 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
The default configuration file /etc/default/atop looks like this:
# /etc/default/atop
# see man atoprc for more possibilities to configure atop execution
LOGOPTS=""
LOGINTERVAL=5
LOGGENERATIONS=2
LOGPATH=/var/log/atop
I configured it with the following settings:
# 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
📓 Note: The
LOGINTERVALdetermines how frequently atop samples system metrics. I chose 5 seconds as a balance between capturing transient issues and minimizing log storage. For even more granular debugging during specific time windows, you can temporarily set this to 1 second, though be aware this will increase log file sizes significantly.
📓 Note:
LOGGENERATIONS=2means atop will keep logs forLOGGENERATIONS + 2 = 4 days. This is particularly important on cloud servers where system disk space is limited. Adjust this value based on your available storage and troubleshooting needs.
Finally, enable and start the atop service:
# Enable atop to start on boot
systemctl enable atop
# Start the atop service immediately
systemctl start atop
# Verify it's running
systemctl status atop
Using atop to Diagnose Issues
Once atop is running, it saves logs to /var/log/atop/ directory. When an issue occurs, you can retroactively examine what happened.
How to Check a Saved Log
Basic command: Use the -r option followed by the path to the log file.
# View historical data for a specific date
atop -r /var/log/atop/atop_20211021
View today's log: If you want to view the log for the current day, atop will automatically select the correct file if you omit the filename.
# Automatically opens today's log
atop -r
Navigate Through the Log
Once the log is open, use the following keys to navigate through time:
| Key | Function |
|---|---|
t | Move forward to the next snapshot in time |
T (Shift+t) | Move backward to the previous snapshot |
b | Jump to a specific point in time. You will be prompted to enter the time (e.g., HH:MM) |
Example workflow:
- Open the log:
atop -r /var/log/atop/atop_20211021 - Press
band enter the time when the issue occurred (e.g.,17:23for 5:23 PM) - Use
tandTto move forward and backward through snapshots around that time
Filter and Sort the Output
While viewing a historical log, you can use these keys to filter and sort the data:
| Key | Function |
|---|---|
C | Sort by CPU usage |
M | Sort by memory usage |
D | Sort by disk usage |
N | Sort by network usage, when process network data is available |
A | Automatically sort by the busiest resource |
g | Generic/general output (default view) |
m / d | Switch to memory / disk details |
y | Show thread-level information |
Sorting keys are uppercase; lowercase keys select views or other functions. See the atop manual.
Understanding atop Output
When examining the output, pay special attention to:
Global metrics (top section):
- DSK line, busy column:
busy = io_ms / per_cpu_ms. High values (>70%) indicate I/O bottleneck - CPU line, wait column: Time spent waiting for I/O
- MEM line, swout/swapin: Swap activity (major red flag)
- CPL line: CPU load average - compare to number of cores
Process metrics (bottom section):
- RDDSK/WRDSK: Actual read/write bytes per process
- DSK column: Relative I/O usage percentage among displayed processes
- CPUNR: Which CPU core the process is running on (helps identify CPU binding issues)
Complementary Tool: perf
For deeper analysis beyond what atop provides, perf can capture detailed profiling data:
# 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
The combination of atop for macro-level system health and perf for micro-level code profiling creates a powerful troubleshooting toolkit.
Historical CPU Usage and Process Evidence
Added November 13, 2026, following the Docker logging and monitoring discussion.
A historical CPU chart answers when the host was busy. Identifying which process caused it requires process-level samples from that same period. Installing a tool after an incident cannot reconstruct measurements that were never collected.
| Question | Evidence to collect |
|---|---|
| When was host CPU usage high? | Saved sar records or cloud CPU metrics |
| Which processes used resources during that window? | Saved atop records, captured pidstat output, or a configured cloud process collector |
| What is happening now? | top, htop, or interval-based pidstat samples |
sar for Host History and pidstat for New Process Samples
sar reads system activity records collected by sysstat; installing the package alone does not prove its periodic collector is enabled. Check the distribution's cron or systemd collection configuration and whether dated data files are appearing. Sysstat project
# 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
Some distributions store daily files under /var/log/sa/ instead. Check the date in the report header rather than assuming sa13 means the incident's month. sar manual
pidstat samples individual tasks going forward; it does not recover an old process list from sar files. For a short capture:
# 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
Use the existing atop recording setup when ongoing system and process replay is needed. A recording interval can miss shorter spikes; increasing frequency also increases storage and collection work. pidstat manual, atop manual
Does Aliyun Provide Process Monitoring?
Yes, but an ECS CPU chart alone is not a process history. As documented at the time of this update, CloudMonitor's operating-system monitoring includes Top 5 process metrics. ECS Insight also provides process resource time series and details such as PID, command and runtime, after the instance has been connected to that service. CloudMonitor metrics, ECS Insight
Check that the relevant collector is installed and reporting, then select the incident time range. Coverage, sampling interval and retention depend on the service and configuration; do not assume every ECS instance already has all process data or a universal 30-day retention period. Top 5 sampling is also not an exhaustive process audit.
For disk alerts, compare capacity, I/O, memory and swap around the same timestamp. If container logs are consuming storage, use the separate Docker log management guide; clearing those files does not by itself diagnose a CPU or swap incident.
Diagnostic Steps
Step 1: Identifying the Culprit - kswapd0
After setting up atop and reviewing the historical logs during the downtime window, I sorted the process list by disk usage (pressing D in atop). At the top of the list was a process I hadn't expected: 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
The process kswapd0 was consuming an extraordinary amount of disk I/O, with RDDSK and WRDSK values far exceeding any application process.
Step 2: Understanding kswapd0
But what is kswapd0? A quick search revealed critical information:
kswapd0 is a Linux kernel thread responsible for managing virtual memory. Specifically, it handles memory reclamation by:
- Moving inactive "cold" pages from RAM to swap space
- Freeing up physical memory when the system is under memory pressure
- Balancing memory usage across the system
⚠️ Warning: High CPU or disk usage from kswapd0 is a symptom, not the root cause. It indicates your system is running out of RAM and desperately trying to free memory by swapping data to disk.
Why kswapd0 Causes High IOPS
When physical RAM is exhausted:
- The kernel needs to free memory to accommodate new allocations
- kswapd0 starts moving inactive memory pages to the swap file/partition
- This causes massive disk I/O operations (both reads and writes)
- On cloud servers with limited IOPS quotas, this quickly saturates the I/O capacity
- The system becomes unresponsive as all disk operations queue up behind swap I/O
As one user on Ask Ubuntu explained:
"The process kswapd0 is the process that manages virtual memory. Your machine should have RAM, SWAP, and the EXT4 on your HDD/SSD."
And from Server Fault discussions:
"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."
Important: kswapd0 vs Malware
📓 Note: In rare cases, malware (particularly crypto miners) disguise themselves as "kswapd0". You can verify the legitimacy of the process by:
- Checking its user ID (should be root/UID 0)
- Verifying it's a kernel thread:
ps aux | grep kswapd0- legitimate kswapd0 shows as[kswapd0]with square brackets- Checking its parent process ID (PPID should be 2, kthreadd)
In my case, it was the legitimate kernel process responding to severe memory pressure.
Step 3: Confirming Memory Pressure
To confirm this hypothesis, I checked several memory-related metrics:
# 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'
The results confirmed my suspicion:
- Physical memory (RAM) was at >95% utilization
- Swap space was actively being used
- High values for
si(swap in) andso(swap out) in vmstat output
Step 4: Analyzing Memory Usage in atop Logs
Since I now understood that kswapd0 is a system process for managing swap (virtual memory), I realized this wasn't a disk problem at all—it was a memory problem. I went back to the atop logs and pressed M to sort by memory usage.
Here's the actual atop output from the time of the incident:
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
Key observations from the log:
-
Critical CPU Load:
CPL | avg1 256.79 | avg5 358.68 | avg15 380.30- Load average of 256 on a 4-core system is catastrophic (normal would be <4)
- This indicates extreme resource contention
-
Swap Exhaustion:
SWP | tot 8.0M | free 0.0M- Swap space completely full (0 bytes free!)
- Active swapping:
swout: 8operations in just 10 seconds
-
Memory Pressure:
MEM | tot 15.0G | free 181.8M | avail 840.0M- Only 181MB free out of 15GB (98.8% utilization)
- Available memory critically low
-
Massive Page Scanning:
PAG | scan 3519G- The kernel scanned 3.5TB worth of pages looking for memory to free
- This is kswapd0 in action, desperately trying to reclaim memory
When I examined the process list sorted by memory (m key):
- Multiple
apache2processes, each consuming 1-2% of memory - Each apache2 process: ~225-240MB RSIZE (Resident Size)
- A
nodeprocess consuming 3% (389.7M) at the top - With 378 total processes and limited free memory, the system was constantly swapping
# 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
Step 5: Identifying the Source - WordPress Containers
I could see apache2 processes consuming memory, but I needed to confirm: were these from Docker containers running WordPress?
First, I checked if the apache2 processes were running inside containers by examining their 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
Result:
0::/system.slice/docker-abc123def456789012345678901234567890abcdef1234567890abcdef12345678.scope
The cgroup path contains docker-abc123def456..., confirming this process is running inside a Docker container with ID starting with abc123def456.
Next, I listed all running containers:
docker ps
Key findings from the output:
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
Bingo! The container ID abc123def456 matches a WordPress 6.7.1 container named my-site-wordpress-1.
Alternative Method: Using pstree to trace process hierarchy
The pstree command provides a clear visual of the parent-child relationship:
pstree -p | grep apache2
Output:
|-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)
This clearly shows:
- Two separate
containerd-shimparent processes (PIDs 912159 and 925630) - Each spawning an apache2 master process (PIDs 912181 and 925653)
- Each master process spawning 10+ apache2 worker children
- Total: 20+ apache2 processes across two containers!
Additional verification methods:
# 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.
Additional clues that confirmed WordPress:
-
Process command:
apache2 -DFOREGROUND- Standard WordPress Docker image runs Apache in foreground mode
-
User ownership: All processes run as
www-data- Default user for PHP/Apache in WordPress containers
-
Multiple containers: I actually had two WordPress containers running:
my-site-wordpress-1(container abc123def456)my-other-site-wordpress-1(container def789abc123)- Both competing for memory resources!
-
Network evidence: The atop log showed Docker networking:
docker0bridge interface- Multiple
veth*virtual ethernet pairs - Each WordPress container gets its own virtual network interface
The root cause was now clear: Two WordPress containers, each spawning dozens of apache2 child processes (due to traffic or inefficient configuration), collectively exhausting the 15GB of RAM, forcing kswapd0 to thrash swap, saturating IOPS, and bringing the server down.
Why WordPress spawns so many Apache processes:
Apache spawning many processes and consuming memory is typically due to high traffic or poor configuration, leading to server instability. As explained in a ServerFault discussion on Apache process spawning, the issue stems from how WordPress handles PHP:
"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... This mpm spawns a process per request."
This means:
- WordPress uses mod_php with Apache - PHP is embedded directly into Apache processes
- PHP is not thread-safe - Forces Apache to use the prefork MPM instead of worker/event MPM
- Prefork spawns one process per request - Unlike threaded MPMs that use lightweight threads
- Modern browsers send concurrent requests - A single page load can trigger 10+ concurrent requests for CSS, JS, images, AJAX calls
- Multiply by traffic - Even modest traffic quickly spawns dozens of processes
In my case:
- 2 WordPress containers
- Each container configured with
MaxRequestWorkers: 150(default) - Under load, each container spawned 10-20 active apache2 processes
- 20 processes × 240MB each = 4.8GB just for apache2 workers
- Combined with the node process (389MB) and other services, this pushed the 15GB server past its limit
The Connection: Memory → Swap → IOPS → Downtime
Here's how the chain of events unfolded:
- Apache2 processes consume RAM: Multiple web server processes serving traffic gradually consumed all available physical memory
- Kernel starts swapping: When RAM hit ~95% utilization, the kernel invoked kswapd0 to move inactive memory pages to swap
- Swap thrashing begins: With swap constantly being written to and read from, disk I/O skyrocketed
- IOPS saturation: Aliyun's basic cloud disk IOPS quota was quickly exhausted by swap operations
- System unresponsiveness: All disk operations (including legitimate requests) queued up, making the server appear "down"
- Misleading alert: Aliyun's monitoring showed "high disk usage" instead of clearly indicating "swap thrashing due to memory exhaustion"
Solutions
Now that I understood the root cause, I needed to implement solutions to prevent this from happening again. Here are the approaches I took:
Solution 1: Tune Apache Configuration to Limit Worker Processes
The WordPress Docker containers use Apache with the prefork MPM, which can spawn excessive worker processes. By tuning Apache's configuration, we can limit memory usage.
Step 1: Enter the container as root
⚠️ Important: Use
-u 0to enter as root user. The defaultwww-datauser cannot modify configuration files.
# 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
Step 2: Locate and edit Apache MPM configuration
# 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
Step 3: Adjust the prefork settings
Default configuration (too aggressive for limited memory):
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150 # Too high! Can spawn 150 processes!
MaxConnectionsPerChild 0
</IfModule>
Optimized configuration for memory-constrained environment:
<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>
Key parameters explained:
StartServers: Number of child processes created on startup (reduced from 5 to 2)MaxRequestWorkers: Maximum number of simultaneous connections (reduced from 150 to 20)MaxConnectionsPerChild: Recycle workers to prevent memory leaks (changed from 0/unlimited to 1000)
Calculation for 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
Step 4: Apply the changes
# 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
Step 4a: Additional Apache Optimizations (Optional)
Beyond MPM settings, consider these additional optimizations:
Disable or tune 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
📓 Note: KeepAlive allows multiple requests over a single TCP connection, which is efficient for latency. However, it ties up Apache processes while waiting for subsequent requests. On high-traffic sites with limited memory, disabling it or using a short timeout prevents processes from idling.
Disable unused Apache modules:
# 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)
Each disabled module reduces the memory footprint of every Apache process by 1-5MB, which adds up when running 20+ processes.
Step 5: Make it persistent
The problem with editing files inside a container is they'll be lost if the container is recreated. To make changes persistent:
# 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
Or use a custom Dockerfile:
FROM wordpress:6.7.1
# Copy optimized Apache config
COPY apache-mpm-prefork.conf /etc/apache2/mods-available/mpm_prefork.conf
Alternative Approach: Consider Switching to Event MPM + PHP-FPM
While the prefork MPM solution above works, prefork is inherently memory-inefficient because it creates a separate process for each request. A more modern approach is to use the event MPM with PHP-FPM:
Why this is better:
- Event MPM uses threads instead of processes - Much lower memory overhead
- PHP-FPM separates PHP processing from web serving - Apache handles static content efficiently
- Better resource isolation - PHP crashes don't affect Apache
- Fine-grained PHP process management - Can limit PHP workers independently
Trade-offs:
- ⚠️ More complex setup - Requires reconfiguring WordPress containers
- ⚠️ Compatibility concerns - Some WordPress plugins may have issues with PHP-FPM
- ⚠️ Not a quick fix - Requires rebuilding your Docker setup
💡 Tip: If you frequently face memory issues and have time for a more permanent solution, migrating to event MPM + PHP-FPM is worth considering. However, for immediate relief, stick with the prefork tuning approach described above.
Basic setup (for reference):
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)
Additional Consideration: PHP Script Optimization
Sometimes the root cause isn't Apache configuration but resource-intensive PHP code. If you notice specific WordPress pages causing high memory usage:
Identify problematic scripts:
# 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);
Common WordPress performance issues:
- Inefficient database queries - Poorly coded plugins making N+1 queries
- Unoptimized images - Large images loaded without compression
- Too many active plugins - Each plugin adds memory overhead
- Missing caching - No Redis/Memcached for object caching
- No CDN - Apache serves all static assets
📓 Note: While optimizing PHP code is beyond the scope of this troubleshooting guide, it's worth investigating if Apache tuning alone doesn't solve your memory issues.
Solution 2: Set Docker Container Resource Limits (My Chosen Approach)
Since I use Dokploy for container management, I chose a cleaner solution: setting resource limits directly in the docker-compose.yml file. This approach enforces hard limits at the container level, preventing any single container from consuming all host resources.
Why this approach is better:
- No need to enter containers and modify configs
- Limits are enforced by Docker itself
- Changes persist across container recreations
- Protects the host from OOM (Out of Memory) situations
- Works seamlessly with Dokploy's deployment workflow
Modified docker-compose.yml with resource limits:
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:
Resource Limit Breakdown:
| Directive | Value | Description |
|---|---|---|
limits: memory | 1G | Maximum RAM the container can use. If WordPress tries to exceed this (e.g., during traffic spike), Docker's OOM Killer will stop and restart the container, protecting the host server from crashing. |
limits: cpus | '0.50' | Limits the container to 50% of one CPU core on average. Prevents any single process from monopolizing the host's CPU. |
reservations: memory | 256M | Minimum guaranteed RAM for the container. If the host is under memory pressure, Docker tries to keep this amount available for this service. |
Calculating optimal limits for your environment:
With two WordPress containers on a 15GB RAM server:
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
My configuration:
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
Benefits of this approach:
- Container isolation: One misbehaving WordPress site can't bring down the other
- Predictable memory usage: With 3GB limit × 2 containers = 6GB max, leaving 9GB for system and other services
- Automatic recovery: If a container exceeds limits, Docker restarts it instead of crashing the host
- No configuration drift: Limits are version-controlled in docker-compose.yml
- Works with Dokploy: Simply update the compose file in Dokploy's interface and redeploy
Applying the changes in Dokploy:
- Go to your WordPress application in Dokploy
- Edit the
docker-compose.ymlin the configuration tab - Add the
deploysection with resource limits - Click "Redeploy" to apply changes
- Monitor with
docker statsto verify limits are enforced
# 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%
Result: After implementing these limits, memory usage stabilized, swap activity dropped to zero, and the IOPS saturation issue was completely resolved. The server has been running smoothly without any downtime since.
References
-
一毛钱关系. (2016, December 5). 阿里云服务器IOPS突然跑满,服务器宕机 [Forum post]. Retrieved December 1, 2025, from https://developer.aliyun.com/ask/201990
-
baker668. (2015, February 9). 关于阿里云磁盘不定期出现IO过高的问题 [Forum post]. Retrieved December 1, 2025, from https://developer.aliyun.com/ask/184548
-
程序猿Ricky的日常干货. (2021, July 15). 使用atop和perf分析抖动问题的方法 [Blog post]. CSDN. Retrieved December 1, 2025, from https://blog.csdn.net/rikeyone/article/details/118756581
-
字节跳动技术团队. (2021, December 17). 深入字节版atop: 线上系统的性能监控实践 [Blog post]. 头条号. Retrieved December 1, 2025, from https://www.toutiao.com/article/7042577697628783141/
-
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
-
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/
-
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
-
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
-
Godard, S. (n.d.). Sysstat: System performance tools for Linux. GitHub. Retrieved November 13, 2026.
-
Godard, S. (n.d.). sar manual. Sysstat. Retrieved November 13, 2026.
-
Godard, S. (n.d.). pidstat manual. Sysstat. Retrieved November 13, 2026.
-
Atop project. (n.d.). atop manual. Retrieved November 13, 2026.
-
阿里云. (n.d.). 基础监控和操作系统监控. 云监控文档. Retrieved November 13, 2026.
-
阿里云. (n.d.). 洞察. ECS 洞察文档. Retrieved November 13, 2026.