How to Resolve Linux Out‑of‑Memory Issues with a Swap Partition
When a small 2 CPU / 2 GB Alibaba Cloud instance runs Java, Nginx, MySQL, and Redis, memory quickly exhausts; this guide shows how to create and configure a swap file, set appropriate permissions, enable it at boot, and tune the swappiness parameter to mitigate out‑of‑memory failures.
A 2c2g Alibaba Cloud server hosting a Java backend, Nginx, MySQL and Redis crashes within hours because physical memory is exhausted. Adding swap can relieve pressure, though it may reduce performance, so upgrading hardware is preferable when possible.
One‑click script
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 && \
sudo chmod 600 /swapfile && \
sudo mkswap /swapfile && \
sudo swapon /swapfile && \
sudo echo '/swapfile none swap sw 0 0' >> /etc/fstab && \
sudo echo 'vm.swappiness=10' >> /etc/sysctl.confSwap size recommendation
Swap partition size is suggested to be 1–2 times the physical memory.
Create the swap file
Use the dd command to allocate a file of the desired size. For a 2 GB swap file:
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096Here /swapfile is the file path, bs=1M writes 1 MB per block, and count=4096 creates 4096 MB (≈2 GB) of space.
Set permissions
sudo chmod 600 /swapfileOnly the root user can read or write the swap file, improving security.
Format the file
sudo mkswap /swapfileThis command prepares the file as swap space.
Activate the swap
sudo swapon /swapfileThe swap file becomes active immediately.
Persist across reboots
Add the following line to /etc/fstab so the swap is enabled at boot:
sudo echo '/swapfile none swap sw 0 0' >> /etc/fstabAdjust swappiness
The swappiness kernel parameter controls how aggressively the system uses swap (range 0–100, default 60). To reduce swap usage, set it to a lower value, e.g., 10.
Temporary change: sudo sysctl vm.swappiness=10 Permanent change: add or modify the line in /etc/sysctl.conf:
sudo echo 'vm.swappiness=10' >> /etc/sysctl.confThen edit /etc/sysctl.conf with a text editor, save, and the new value takes effect after a reboot or by running sysctl -p.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
