How to Add Swap Memory to Prevent Out-of-Memory (OOM) Crashes
When your applications consume all physical RAM, the Linux kernel triggers the OOM (Out of Memory) Killer, abruptly terminating high-memory processes like MySQL, Discord bots, or web servers with the error Killed. Configuring a Swap File uses NVMe disk space as emergency virtual memory, preventing sudden system crashes.
- 1 GB - 2 GB RAM VPS: Add 2 GB of swap.
- 4 GB - 8 GB RAM VPS: Add 4 GB of swap.
Step 1: Check Existing Swap
Log in to your VPS via SSH as root and check if swap is already configured:
swapon --show
If the output is empty, your server has no active swap file.
Step 2: Create the Swap File
To create a 2 GB swap file, run the following command (for 4 GB, change 2G to 4G):
fallocate -l 2G /swapfile
If fallocate fails, you can alternatively use: dd if=/dev/zero of=/swapfile bs=1M count=2048.
Step 3: Secure Swap File Permissions
Only the root user should be able to read or write to swap space for security:
chmod 600 /swapfile
Step 4: Format and Activate the Swap File
Set up the Linux swap area and enable it:
mkswap /swapfile
swapon /swapfile
Step 5: Make Swap Permanent Across Reboots
If you reboot your VPS, the swap file will be deactivated unless added to the file system table (/etc/fstab). Run this single command to append it safely:
echo '/swapfile none swap sw 0 0' | tee -a /etc/fstab
Step 6: Verify Active Swap Space
Confirm that your new virtual memory is active by checking your memory statistics:
free -h
The Swap row will now display 2.0Gi (or 4.0Gi), confirming your VPS has virtual memory protection against crashes.
Need More Dedicated Physical RAM?
While swap prevents crashes, physical RAM offers the fastest performance. Upgrade your VPS tier anytime with zero data loss.
Upgrade Your Ash Host VPS這篇文章有幫助嗎?
相關文章
Powered by WHMCompleteSolution