Swap File in Linux: Add 4GB Swap Space in 4 Steps

Quick Linux Tip #94:

Question: My server is low on RAM but has no swap partition. How do I add swap?

Try:
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

Info: fallocate preallocates space instantly without writing zeros. chmod 600 secures swap permissions, mkswap formats the file, and swapon activates it immediately.

Examples:

  • $ sudo swapoff /swapfile && sudo rm /swapfile  # Safely remove active swap file
  • $ sudo sysctl vm.swappiness=10  # Reduce swap usage aggressiveness
  • $ free -h  # Verify total and active swap allocation

Note: chmod 600 is critical because swap memory can store unencrypted secrets. Add /swapfile none swap sw 0 0 to /etc/fstab to persist across reboots.




LinuxTeck.com
linuxteck:~$ sudo fallocate -l 4G /swapfile

linuxteck:~$ sudo chmod 600 /swapfile

linuxteck:~$ sudo mkswap /swapfile
Setting up swapspace version 1, size = 4 GiB (4294967296 bytes)
no label, UUID=1a2b3c4d-5e6f-7890-abcd-ef1234567890

linuxteck:~$ sudo swapon /swapfile

linuxteck:~$ swapon --show
NAME      TYPE SIZE USED PRIO
/swapfile file 4G   0B   -2

linuxteck:~$ echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
linuxteck:~$

PREVIOUS ARTICLE Quick Linux Tip #93: Strace -c Command: Find Slow System Calls in Linux NEXT ARTICLE Quick Linux Tip #95: Linux Package Comparison: Find Differences Between 2 Servers
About John Britto

John Britto Founder & Chief-Editor @LinuxTeck. A Computer Geek and Linux Intellectual having more than 20+ years of experience in Linux and Open Source technologies.

View all posts by John Britto →

Leave a Reply

Your email address will not be published.