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.

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.