Linux - Create swap file

By xngo on May 3, 2020

On a low memory system such as a VPS with less than 512MB of RAM, it is always good to create a swap file.

# Allocate 1GB of disk space for swap file.
    fallocate -l 1G /tmp/swapfile
 
# Set permission.
    chmod 600 /tmp/swapfile
 
# Make it a swap file.
    mkswap /tmp/swapfile
 
# Turn swap file on.
    swapon /tmp/swapfile
 
#  Show memory and swap used.
    free -h
 
# Show swap file / partition.
    swapon --show
 
# Remove swap.
    swapoff -v /tmp/swapfile
    rm /tmp/swapfile
  • If you run swapon /tmp/swapfile and get the error message: "swapon: /tmp/swapfile: swapon failed: Invalid argument". Ensure that /tmp/swapfile is not on the memory filesystem. Change swapfile path to a normal filesystem partition.
  • If you get bash: mkswap: command not found, then install util-linux package: apt-get install util-linux. If the package is already installed, then just call the executable using the the full paths, i.e. /sbin/mkswap, /sbin/swapon.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.