On a 1–2 GB VPS, running out of memory can crash your database or web server. zram creates a compressed block device in RAM and uses it as swap, so rarely used pages are squeezed rather than written to slow disk. It often gives noticeably more usable memory on small servers.
Before you start
- A KVM VPS (OpenVZ/LXC containers usually cannot set up swap; see OpenVZ explained).
- Check current memory and swap with
free -handswapon --show.
zram vs swap file
| zram | Swap file on disk | |
|---|---|---|
| Speed | Fast (RAM + compression) | Much slower |
| CPU cost | Some, for compression | Minimal |
| Disk wear and I/O | None | Yes |
| Capacity | Limited by RAM and compression ratio | Limited by disk |
They can be combined: zram with higher priority, a small disk swap file as a last resort. See create a swap file.
Set up on Debian/Ubuntu with zram-tools
sudo apt install -y zram-toolsEdit /etc/default/zramswap:
ALGO=zstd
PERCENT=50
PRIORITY=100sudo systemctl restart zramswapSet up with systemd zram-generator
On Fedora-family systems and others that package zram-generator (on AlmaLinux/Rocky it may require EPEL or a manual build), create /etc/systemd/zram-generator.conf:
[zram0]
zram-size = ram / 2
compression-algorithm = zstd
swap-priority = 100sudo systemctl daemon-reload && sudo systemctl start systemd-zram-setup@zram0Tune swappiness
With fast zram swap, a higher swappiness is reasonable:
echo "vm.swappiness=100" | sudo tee /etc/sysctl.d/99-zram.conf && sudo sysctl --systemStart there and adjust if you see unwanted swapping of active processes.
Check that it works
swapon --showzramctlzramctl shows the original data size and compressed size, so you can see the compression ratio.
Limits
- zram is not a substitute for enough RAM: if the working set does not fit, performance drops.
- Compression uses CPU; on a VPS with heavy CPU steal it helps less.
- Fix memory-hungry settings (PHP-FPM children, database buffers) first; see high RAM usage.
Frequently asked questions
Should zram be half my RAM?
50% is a common default; it is a maximum, and only compressed pages actually use memory.
Which algorithm is best?
zstd gives a good ratio; lz4 is faster with less compression.
Will zram help MySQL?
It helps the system survive memory peaks, but database buffers should be sized to fit RAM.
