A swapfile is used by Linux when processes run out of memory. Rather than crashing, the process will be allowed to use a chunk of the disk, which is significantly slower, but prevents unintended out-of-memory crashes that can harm service availability.
What is a Swapfile?
Let us start by a rhetorical question: what happens when your computer runs out of memory?
In Linux, a special monitoring process – the OOM monitoring/killer process – will monitor whether a system is running out of memory, unless the OOM killer was disabled or configured differently.
When that happens, this process will terminate one of the processes running on the system in order to free memory. This can lead to painful results like data corruption or unavailable services. The acronym OOM stands for “Out of Memory”
One solution is to buy additional memory or to reduce the number of programs or services running simultaneously on the computer or server. But how about if we could use some our (usually cheap) disk space as “extra memory”?
That is exactly what a swapfile is and does: a special file created on your storage device which then becomes part of the main memory. Not directly, and there is processing overhead, but indirectly and with considerable processing speed impact.
Swapfile Advantages and Disadvantages
Main memory is usually ultra fast when compared with slower disks. Even SSD’s (solid state drives) are almost always slower then high-speed main memory chips. For HDD’s (mechanical, spinning, traditional hard disk drives) the difference in speed is much bigger still.
It is therefore a distinct advantage, in most setups, to use a slower disk (SDD and especially HDD) as a source of memory. The delay of writing data back and forth between main memory and disk (i.e. using the disk as memory) is called ‘swapping’ (swapping out memory with disk space)
That said, it is always a good idea to have a reasonably sides swap file on your system. The reason is simple; let’s say that we only require 1 extra Gigabyte of memory for a period of a few minutes to ensure our system does not invoke the OOM killer and terminates some processes. A swapfile is better in this case because even if a process runs out of usable RAM, it won’t crash, just run slower for a bit until it finishes its task.
However, if the system starts swapping heavily, it will almost definitely become slower (read: much slower). This will be very noticeable.
In summary, there is a fine and delicate balance, which is somewhat arbitrary and depends on many different things within a given situation; the number of processes running on a system and their memory working sizes, the total memory in use, the memory available in the swap file, the specific swap file configuration of the system etc.
Some Swapfile Considerations
On many Linux setups in the world today, there is a swap partition assigned on one of the disks within the system. This is a special area, usually (but not exclusively; it can be added later) reserved during the installation of the Linux operating system. It has the same the target functionality is the same as that of a swapfile. To check if your system has some form of swap currently enabled, simply execute the following in your terminal:
sudo apt -y install htop htop
And locate the following output:
Notice how on this system, there is 62.7G main memory, and 11.0G swap space. You can also see how only a small amount (23.5M) is currently in use. If you suspect your system is swapping, check how these two counters look.
If they are both near-full, your system is highly likely swapping heavily and will run significantly slower. The reason is that now there is a heavy I/O bound (i.e. disk bound) load, constantly swapping main memory with disk based memory.
As a rule of thumb, some people prefer to use a certain percentage of system memory as the size to be allocated to a swap file. I personally take another route, and that is to consider how much additional memory I may need. If the size is considerable, for example a server with 8GB will likely end up using 14GB for a specific use case, then it makes much more sense to raise the server memory from 8GB to 16GB.
However, if the system has 8GB and the usual use is 6-7GB with an occasional spike if I start too many programs at once, I may consider a 8GB additional swap space, or slightly more. Disk space is usually quite cheap, so over sizing it a little, provided you have the space, won’t hurt.
How to Enable a Swapfile
Ready to add a swapfile? This can be done on the fly. This method will work on both Debian (Ubuntu, Mint, …) as well as RedHat (RedHat, Centos, …) based systems.
We will be creating a 1 Gigabyte, or 1000 Megabyte, or 1024000 Blocks (calculated as the number of Megabytes x 1024) swapfile in this example.
We will name it swapfile123, located in the root (/) directory, and we have given it that name to avoid overwriting any file you may already have in place. If you are confident you do not have any file named /swapfile, you may use that instead if you like, taking care to change the filename at all places correctly.
Please make sure to type any commands, and especially the
dd command, carefully in order not to overwrite any data on your system. We use
sudo su to enter superuser (su) mode via
sudo. It is much the same as executing each command using
sudo, though it is easier not to type each sudo command prefix by using this way.
sudo su if [ -r /swapfile123 ]; then echo "Stop please! /swapfile123 already exists!"; fi dd if=/dev/zero of=/swapfile123 bs=1024 count=1024000 chmod 0600 /swapfile123 mkswap /swapfile123 swapon /swapfile123
You should see output similar to the following:
If so, congratulations! You have just enabled your first swapfile, dynamically (on the fly), at the Linux command line!
First we used the
dd tool to create our swapspace, using the
/dev/zero device (a virtual device which just outputs zero’s when called, by
dd or any other tool). Next we set some appropriate security privileges.
We next indicated to the operating system that the file was to be made a swapfile using the
mkswap command. Finally we turned on the swapspace, dynamically at the command line, without having to restart our system.
We can also easily check if our swap space has become larger by using
Great, you can see how we went from 12215M to 11215M (-1000M as expected) when we deactivated the newly created swapfile. You can also see how we used
swapoff to dynamically turn off swap at the command line.
It is nice to know that if we ever see our system getting into memory issues, and we can type fast enough, we are able to give it extra memory on the fly :) In practicality, it is better to do this upfront before issues occur.
We now only have one small issue to address. If we were to reboot at this time, whilst our swapfile would remain on the disk, the system would not be using it. No setting change was made so far which will ensure that the swapspace is reloaded on system reboot.
Enabling Our New Swap at Boot Time
To enable the new swap space at boot time, simply add the following line (as the line) to /etc/fstab:
/swapfile123 swap swap defaults 0 0
You can do so while still in
sudo su mode (as indicated by the leading
#) by starting the nano editor for /etc/fstab:
nano /etc/fstab cat /etc/fstab
Then simply add the line above to the file at the end and save (CTRL+X > Y > enter). Do not modify or delete any other lines as this may result in your system not booting correctly anymore. Also make sure to double check the contents of your /etc/fstab file before restarting by executing the
cat /etc/fstab above.
You can now reboot your system and confirm that your extra swap space is still available by using
free -m again.
Removing Our New Swap Space
If you want to remove the new swap space, or perhaps create a somewhat larger one, you can do this by editing the /etc/fstab file again first, and removing the line which loads the swap file in full. Do not modify or delete any other lines as this may result in your system not booting correctly anymore! You can then execute:
sudo swapoff /swapfile123 rm /swapfile123
All done! No need to reboot either, as this change was made dynamically. On the next reboot, the swapfile will not be activated anymore as we removed the matching line from the /etc/fstab file.
- › Does Hibernating My PC Save More Energy Than Sleep?
- › How Much Does It Cost to Operate an Electric Lawn Mower?
- › What’s New in Windows 11’s 22H2 Update: Top 10 New Features
- › What Are the Best Nintendo Switch Games in 2022?
- › Picsart Gold Review: A True Treasure for Quick Photo and Video Editing
- › Don’t Put Your TV Over Your Fireplace