Working With Linux SWAP Space The Easy Way

Table of Contents

Are you new to Linux and have often wondered, what is swap space in Linux? I guarantee many of you newcomers have launched HTOP or even System Monitor and saw that SWAP space graph and asked yourself that same question.

So what is Linux SWAP space? Simply put, SWAP is extra Virtual Memory that Linux can use when you run out of physical RAM. If you’re coming from our… eh… old friend Windows, its basically the same concept as the Page File. Simple, right? Okay, let’s see how to add SWAP space!

Linux SWAP Space Recommendations

Alright, so before we continue with the fun part, we have to address what we need to know about Linux SWAP space. The catch is that you have to sacrifice disk space from your hard drive. How much disk space? Ehh that can differ depending on what you have going on inside your system. Let’s look at what our friends at Fedora have to say about this.

Amount of RAM in the system Recommended swap space Recommended swap space if allowing for hibernation
< 2GB
2 times the amount of RAM
3 times the amount of RAM
2GB – 8GB
Equal to the amount of RAM
2 times the amount of RAM
8GB – 64GB
0.5 times the amount of RAM
1.5 times the amount of RAM
> 64GB
4GB of swap space
No extra space needed

Fedora is a big boy in the Linux ecosystem, so I’d say we can trust them in their judgement. Personally, I like to give myself 4GB of SWAP space each time since I usually have plenty of RAM as it is. Using the chart, decide just how much Linux SWAP space you want to give yourself.

Linux SWAP Space Scenarios

Now for the fun part! BUT, before we continue we also have to discuss the 2 ways we can add SWAP space. The first method is to use a SWAP File and the second being a SWAP Partition directly on our HD. What is the difference between using a SWAP File and a SWAP Partition?

Using a SWAP File can actually be detrimental in some cases. Why? Well since you are using a file for SWAP, when your system decides to use this SWAP File it will increase I/O on that partition. Secondly, it can complicate hibernation if you use it and increase the chances of corruption. For these reasons and more, SWAP Files are generally not used. If you have a fast enough HD and you choose to use a SWAP File… I guess? Just be sure you’re aware of the risks!

Using a Linux SWAP Partition is the preferred method of adding SWAP space to your system. Not only is it separate from your root partition but it is using the block device directly making it more efficient and reliable. Are there any downsides? Sadly, yes but also maybe not? I can picture 2 scenarios.

Scenario 1

You make a clean install of your favorite Linux distribution and your HD is partitioned for 4GB SWAP and the rest for boot and your root filesystem. Eventually, you’re such a RAM hog that you need to expand your SWAP to remedy your limited RAM. Here it becomes difficult because we have a fixed partition that is no longer easily expandable and may require a re-install of your Linux distribution.

Scenario 2

You make a clean install of your favorite Linux distribution and your HD is partitioned for just boot and the root filesystem. You then use a separate block device or HD for your SWAP space. In this scenario, if the HD is large enough and used only for SWAP space, then you can just as easily increase and decrease the SWAP space as needed.

Knowing this, you decide what is best for your use case. I’m here to show you how to setup both methods!

Linux SWAP File

Create

So, as discussed by our friends at Fedora. We need to create a swap file based off how much RAM we currently have on our machine. My VM only has 4G, therefore I’m going to create a SWAP file of 4G.

				
					sudo fallocate -l 4G /swapfile2
				
			

My Ubuntu VM already has a swapfile called "swapfile" in the root directory (/). Therefore, I will be naming my new SWAP file "swapfile2".

Configure the correct permissions for your new swapfile so only root has access to it.

				
					sudo chmod 600 /swapfile2
				
			

Finally, mark our new swapfile as swap space!

				
					sudo mkswap /swapfile2
				
			

Mount

You successfully created the swapfile! What’s that? How do you actually use it, now?

There are 2 ways of going about this. One, is to use the swapon command and temporarily mount the swapfile. The problem with this, is the swapfile is not permanent. On reboot, it will be gone! Well, not mounted, to be exact.

We want to mount it permanently so instead we are going to mount it on startup using fstab.

				
					sudo vim /etc/fstab
				
			
				
					# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/vda5 during installation
UUID=718ee24b-4b12-4bad-93d5-79aee28c8bf0 /               ext4    errors=remount-ro 0       1
# /boot/efi was on /dev/vda1 during installation
UUID=FC8F-4225  /boot/efi       vfat    umask=0077      0       1
/swapfile                                 none            swap    sw              0       0
/swapfile2                              none            swap    sw              0       0
				
			

The last line in the example above is our swapfile. Once you are finished, save changes and reboot!

Once you reboot, run the following command and verify the swapfile is active.

				
					linuxman@linuxman:~$ swapon -s
Filename				Type		Size	Used	Priority
/swapfile2                             	file    	4194300	0	-2
/swapfile                              	file    	945416	0	-3
				
			

Looks like it is working!

Linux SWAP Partition

Create

Now for the big boy method.

In my example, I have added a 4G Virtual HD to use for my swap space, so if you are using a real HD much larger than that, you will have to partition that HD only to the size that you need it to be.

I’ll go ahead and use fdisk to make a new Linux SWAP partition.

				
					linuxman@linuxman:~$ lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
vda    252:0    0    20G  0 disk 
├─vda1 252:1    0   512M  0 part /boot/efi
├─vda2 252:2    0     1K  0 part 
└─vda5 252:5    0  19.5G  0 part /
vdb    252:16   0     4G  0 disk 
				
			

Here we see that my swap disk will be /dev/vdb. So I will go ahead and create the partition for my swap.

				
					linuxman@linuxman:~$ sudo fdisk /dev/vdb
Welcome to fdisk (util-linux 2.34).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Device does not contain a recognized partition table.
Created a new DOS disklabel with disk identifier 0xedcdaa54.

Command (m for help): p
Disk /dev/vdb: 4 GiB, 4294967296 bytes, 8388608 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xedcdaa54

Command (m for help): n
Partition type
   p   primary (0 primary, 0 extended, 4 free)
   e   extended (container for logical partitions)
Select (default p): 

Using default response p.
Partition number (1-4, default 1): 
First sector (2048-8388607, default 2048): 
Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-8388607, default 8388607): 

Created a new partition 1 of type 'Linux' and of size 4 GiB.

Command (m for help): t
Selected partition 1
Hex code (type L to list all codes): L

 0  Empty           24  NEC DOS         81  Minix / old Lin bf  Solaris        
 1  FAT12           27  Hidden NTFS Win 82  Linux swap / So c1  DRDOS/sec (FAT-
 2  XENIX root      39  Plan 9          83  Linux           c4  DRDOS/sec (FAT-
 3  XENIX usr       3c  PartitionMagic  84  OS/2 hidden or  c6  DRDOS/sec (FAT-
 4  FAT16 <32M      40  Venix 80286     85  Linux extended  c7  Syrinx         
 5  Extended        41  PPC PReP Boot   86  NTFS volume set da  Non-FS data    
 6  FAT16           42  SFS             87  NTFS volume set db  CP/M / CTOS / .
 7  HPFS/NTFS/exFAT 4d  QNX4.x          88  Linux plaintext de  Dell Utility   
 8  AIX             4e  QNX4.x 2nd part 8e  Linux LVM       df  BootIt         
 9  AIX bootable    4f  QNX4.x 3rd part 93  Amoeba          e1  DOS access     
 a  OS/2 Boot Manag 50  OnTrack DM      94  Amoeba BBT      e3  DOS R/O        
 b  W95 FAT32       51  OnTrack DM6 Aux 9f  BSD/OS          e4  SpeedStor      
 c  W95 FAT32 (LBA) 52  CP/M            a0  IBM Thinkpad hi ea  Rufus alignment
 e  W95 FAT16 (LBA) 53  OnTrack DM6 Aux a5  FreeBSD         eb  BeOS fs        
 f  W95 Ext'd (LBA) 54  OnTrackDM6      a6  OpenBSD         ee  GPT            
10  OPUS            55  EZ-Drive        a7  NeXTSTEP        ef  EFI (FAT-12/16/
11  Hidden FAT12    56  Golden Bow      a8  Darwin UFS      f0  Linux/PA-RISC b
12  Compaq diagnost 5c  Priam Edisk     a9  NetBSD          f1  SpeedStor      
14  Hidden FAT16 <3 61  SpeedStor       ab  Darwin boot     f4  SpeedStor      
16  Hidden FAT16    63  GNU HURD or Sys af  HFS / HFS+      f2  DOS secondary  
17  Hidden HPFS/NTF 64  Novell Netware  b7  BSDI fs         fb  VMware VMFS    
18  AST SmartSleep  65  Novell Netware  b8  BSDI swap       fc  VMware VMKCORE 
1b  Hidden W95 FAT3 70  DiskSecure Mult bb  Boot Wizard hid fd  Linux raid auto
1c  Hidden W95 FAT3 75  PC/IX           bc  Acronis FAT32 L fe  LANstep        
1e  Hidden W95 FAT1 80  Old Minix       be  Solaris boot    ff  BBT            
Hex code (type L to list all codes): 82
Changed type of partition 'Linux' to 'Linux swap / Solaris'.

Command (m for help): p
Disk /dev/vdb: 4 GiB, 4294967296 bytes, 8388608 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xedcdaa54

Device     Boot Start     End Sectors Size Id Type
/dev/vdb1        2048 8388607 8386560   4G 82 Linux swap / Solaris

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.
				
			

The output is a bit… flooded, but basically I created a new partition using the default values. Then set the partition type to SWAP using the type code 82. Last, I printed the new partition table to see the results and saved changes.

Like before, we have to mark our partition as swap space. But first, we have to force Linux to re-read the partition tables without rebooting. Handy little trick, no? To do this, we use the partprobe command followed by the mkswap command.
				
					sudo partprobe; sudo mkswap /dev/vdb1
				
			

Mount

Now, mounting is going to be slightly different. To make sure that we never have to worry about the wrong partition being mounted in the event that the block device path changes. We will use the UUID of the swap partition we created!

To do this, we are going to use the blkid command to dump all the pretty UUIDs on our system.

				
					linuxman@linuxman:~$ blkid
/dev/vda5: UUID="718ee24b-4b12-4bad-93d5-79aee28c8bf0" TYPE="ext4" PARTUUID="086b839d-05"
/dev/vda1: UUID="FC8F-4225" TYPE="vfat" PARTUUID="086b839d-01"
/dev/vdb1: UUID="615bbcff-5f05-429f-acf3-5fdbd3c6d40c" TYPE="swap" PARTUUID="edcdaa54-01"
				
			
Here we see our UUID for vdb1 is 615bbcff-5f05-429f-acf3-5fdbd3c6d40c. So, using fdisk again, we mount using the UUID.
				
					# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/vda5 during installation
UUID=718ee24b-4b12-4bad-93d5-79aee28c8bf0 /               ext4    errors=remount-ro 0       1
# /boot/efi was on /dev/vda1 during installation
UUID=FC8F-4225  /boot/efi       vfat    umask=0077      0       1
/swapfile                                 none            swap    sw              0       0
UUID=615bbcff-5f05-429f-acf3-5fdbd3c6d40c none swap sw 0 0
				
			

Finish adding that boi to your startup and reboot!

When you come back, let’s check our swappies again.

				
					linuxman@linuxman:~$ swapon -s
Filename				Type		Size	Used	Priority
/swapfile                              	file    	945416	0	-2
/dev/vdb1                              	partition	4193276	0	-3
				
			

Nice! We’re now using an actual disk for our swap partition. Along the way, you even got exposure to some new, fancy and handy commands to help you along your Linux journey.

Meet the Author

Leave a Reply