Running 100 Docker Containers on a 2GB RAM VPS: Mastering ZRAM and KSM for Extreme Resource Optimization
Introduction: The Challenge of Low-Spec Virtual Private Servers
In the world of DevOps and cloud hosting, resource allocation is a constant balancing act between cost and performance. Small businesses, developers, and hobbyists frequently deploy workloads on budget Virtual Private Servers (VPS) configured with just 2GB of RAM. Under normal circumstances, hosting a handful of microservices or Docker containers on such a machine would quickly exhaust its memory, triggering the dreaded Linux Out-Of-Memory (OOM) Killer and crashing vital applications.
However, what if you could scale your deployment density by a factor of ten? Imagine running up to 100 Docker containers smoothly on that exact same 2GB RAM VPS. While it sounds impossible, leveraging advanced Linux kernel features makes this extreme optimization entirely achievable. By combining ZRAM (compressed RAM swap) and KSM (Kernel Samepage Merging), you can maximize your memory efficiency, eliminate disk-thrashing bottlenecks, and dramatically reduce your infrastructure overhead.
Understanding the Core Bottleneck: Docker Memory Overhead
Before diving into the solution, it is vital to understand why Docker containers consume memory. While Docker is inherently more lightweight than traditional Virtual Machines (VMs) because it shares the host OS kernel, each running container still requires dedicated user-space memory. This includes:
- The runtime application footprint (e.g., Node.js, Python, Nginx processes).
- Shared libraries duplicated across multiple independent container filesystems.
- Internal container management structures managed by the Docker daemon.
When deploying 100 identical or similar microservices, the baseline memory duplication becomes staggering. Standard Linux swap space on an SSD or NVMe drive can act as a safety net, but disk I/O operations are orders of magnitude slower than RAM. Relying on traditional swap leads to thrashing, a state where the CPU spends all its cycles moving memory pages between RAM and disk, rendering the server completely unresponsive.
The Dual Engines of Optimization: ZRAM and KSM
To overcome the memory wall without upgrading to an expensive VPS plan, we introduce two powerful, kernel-level memory management technologies: ZRAM and KSM. Together, they form a highly symbiotic relationship that compresses and deduplicates memory dynamically.
1. ZRAM: Fast, In-Memory Compression
Instead of swapping idle memory pages out to a slow block storage disk, ZRAM creates a compressed block device directly inside the system's volatile memory. When the system requires swap space, the kernel redirects those pages to ZRAM, which compresses them using high-speed algorithms like lz4 or zstd.
Key Insight: ZRAM effectively multiplies your available memory capacity. A typical compression ratio of 3:1 means that 1GB of physical RAM allocated to ZRAM can hold up to 3GB of uncompressed data, sacrificing only a fraction of CPU cycles for rapid compression and decompression.
2. KSM: Kernel Samepage Merging
Originally developed for KVM virtualization, Kernel Samepage Merging (KSM) is a background daemon that scans system memory for anonymous pages that contain identical content. When duplicates are found, KSM merges them into a single, write-protected page shared among the processes. If a container needs to modify its shared page, the kernel automatically generates a private copy using a Copy-on-Write (CoW) mechanism.
When running dozens of similar Docker containers—such as multiple instances of Alpine Linux, Ubuntu base images, or identical Node.js runtimes—KSM identifies thousands of redundant memory pages and fuses them together, freeing up massive amounts of physical RAM.
Step-by-Step Implementation Guide
Let us walk through the process of configuring ZRAM and KSM on a clean Ubuntu/Debian-based 2GB RAM VPS. Ensure you have root or sudo privileges before proceeding.
Step 1: Disabling Traditional Swap
To ensure our system prioritizes high-speed ZRAM over slow disk swap, we must disable any existing file-based or partition-based swap mechanisms.
- Disable all active swap devices:
sudo swapoff -a - Edit the
/etc/fstabfile and comment out or remove any lines pointing to swap files or partitions.
Step 2: Installing and Configuring ZRAM
We will use the zram-tools package, which automates the initialization and integration of ZRAM devices into the standard Linux memory management pipeline.
- Install the required utilities:
sudo apt update && sudo apt install zram-tools -y - Open the configuration file for editing:
sudo nano /etc/default/zramswap - Configure the parameters to allocate a generous portion of memory for compression, utilizing the modern, balanced
zstdalgorithm:
CORES=1
ALGO=zstd
SIZE=2048
PRIORITY=100
Save the file and restart the ZRAM service: sudo systemctl restart zramswap. You can verify its operation by running swapon --show, which should display your active ZRAM block device.
Step 3: Enabling and Optimizing KSM
KSM is natively compiled into most modern Linux kernels but is often disabled by default to save minor CPU overhead on non-virtualized systems.
- Enable the KSM daemon immediately:
echo 1 | sudo tee /sys/kernel/mm/ksm/run - To make this change permanent across reboots, add the following line to your
/etc/rc.localfile or create a dedicated systemd service:
# Append to startup scripts
echo 1 > /sys/kernel/mm/ksm/run
To maximize the efficiency of page merging for a high density of containers, tune the scanning frequency and aggressiveness via the sysfs interface:
echo 1000 | sudo tee /sys/kernel/mm/ksm/pages_to_scan(Defines how many pages to scan in a single pass)echo 20 | sudo tee /sys/kernel/mm/ksm/sleep_millisecs(Defines the delay between scans in milliseconds)
Deploying 100 Docker Containers Responsibly
With ZRAM providing a massive compression buffer and KSM actively stripping out duplicate memory pages, your VPS is ready for dense workloads. However, deployment requires strict structural discipline to prevent sudden CPU spikes or uncontrolled resource consumption.
When launching your 100 containers, it is critical to use Docker memory limits. Restricting each container ensures that an isolated memory leak in one microservice cannot cascade and bring down the entire node. For example, when launching containers via Docker Compose or CLI, append strict hardware limitations:
docker run -d --name app-instance-1 -m 32m --memory-swap 64m nginx:alpine
By enforcing a 32MB physical memory ceiling per container, 100 containers will theoretically request 3.2GB of memory. Thanks to KSM deduplicating the shared Alpine Linux libraries and Nginx binaries, and ZRAM compressing the idle operational runtime data, your physical 2GB RAM node will easily maintain an optimal operating temperature and stable performance metrics.
Monitoring and Verifying System Health
Maintaining long-term stability requires continuous observation. Use the following built-in diagnostic utilities to monitor memory health in real-time:
- htop / top: Monitor overall memory allocation and ensure CPU consumption remains steady during KSM scanning cycles.
- cat /sys/kernel/mm/ksm/pages_shared: Tracks how many identical memory pages have been successfully merged into a single footprint. Higher numbers signify greater efficiency.
- cat /sys/kernel/mm/ksm/pages_sharing: Shows how many extra pages are being saved through deduplication, highlighting your exact infrastructure ROI.
Conclusion: High Efficiency Without Extra Hardware Costs
Running 100 Docker containers on a 2GB RAM VPS transitions from an impossible pipe dream to a practical reality when you unlock the full capabilities of the Linux kernel. By combining ZRAM's lightning-fast in-memory compression with KSM's intelligent memory page deduplication, you drastically lower the cost barrier for hosting microservices, staging environments, and sandboxed test labs.
Implement these optimizations on your low-spec instances today, enforce strict container memory limits, and enjoy enterprise-level deployment densities without spending a single extra dime on cloud hardware upgrades.
