It’s Easier Than You Think…
So I’m a bit tired of seeing complicated and verbose solutions for creating a swapfile on Linux.
It’s actually very simple to do this.
Creating a swapfile makes swap space available for your Linux system.
And swap space is an essential component of a well-functioning system.
It’s used primarily to free up RAM when you’re running low on memory as well as handling memory management (this becomes hard for the kernel to accomplish without swap space).
In this post we’ll be making a swapfile in the terminal so we can in turn, create swap space for our system.
Anyways, let’s just jump into the steps on how to do this.
Step 1 - Creating A Swapfile
$ sudo fallocate -l 4G /swapfile
Here we’re using the
fallocate tool to create a 4GB swapfile in the root directory.
Step 2 - Prep The Swapfile For Use
Next we’ll need to prepare the swap file with the
mkswap command before it can actually be used.
We can do this like so:
$ sudo mkswap /swapfile
Step 3 - Change Permissions For Swapfile
For this step we need to change the default permissions so that only root can use the swapfile (this is a good practice for added security).
We can use the
chmod command to change the file permissions:
$ sudo chmod 600 /swapfile
It’s worth nothing that this removes all permissions from group members as well as other users.
Only the file owner and root are able to read and write to the swapfile.
Step 4 - Activating The Swapfile
Here we’ll be using the
This informs Linux that there’s a swapfile available for use.
To use the
swapon command, we only need to provide it the location and filename:
$ sudo swapon /swapfile
The swapfile is now active!
Step 5 - Add Your Swap File To fstab
Now we need to ensure that our swap file is available after restart.
To do this, we need to add the swap file to the /etc/fstab file.
You will need a text editor for this. For this example, we’ll be using the small, but mighty, Gedit text editor.
First we’ll open up the
/etc/fstab file with gedit:
$ sudo gedit /etc/fstab
Next, we’ll copy and add this line to the bottom of the file:
/swapfile none swap sw,pri=10 0 0
After adding this line, restart your computer.
Step 6 - Confirm That The Swap Space Is Being Used
Alright, the final step…
Now we’ll use the
swapon command with the
This will let you know if there is a swapfile in use.
$ swapon --show NAME TYPE SIZE USED PRIO /dev/sda2 partition 4G 0B 10
And this confirms that our swapfile is indeed being used. Hooray!
That is it…
You’ve just learned how to easily create swap space on your Linux system.
Share your thoughts…
Feel free to leave a comment about your experiences with creating swap space on your system.
Were they positive or negative?
Anything else you’d like to add? Share below…