How to create swap partition in Linux

This tutorial explains how to view, list, activate, deactivate, add, remove, increase, decrease mount and format swap space and swap partition in Linux step by step with practical examples. Learn essential swap space management tasks including what swap space is and how swap space is used in Linux.

What is the swap space?

Traditionally Linux was developed for server system. Server systems are built to process several processes simultaneously. Sometime some process may use more than expected memory. For example a university website which is hosted in Linux server system may consume more memory on the day when exam result is announced. This kind of memory spike is very common in server system. Any service may use more memory in its peak time. Linux uses swap space to deal with the shortage of physical memory. The swap space is the space of hard disk that can be used as the memory.

swap hard disk ram

Let’s understand it in more detail. System divides RAM in smaller chunks known as memory pages. Memory pages are assigned to service or process running in CPU. CPU processes services or applications in round-robin fashion.

Round-robin Fashion

In round-robin fashion, all processes are scheduled in a queue based on time sharing technique. Further each process is assigned a quantum (allowed CPU Time slot). If process is not finished in allowed time slot then it will be terminated and resumed next time when this process gets its next time slot. For example, if the time slot is 100 milliseconds, and job1 takes a total time of 250 ms to complete, the round-robin scheduler will suspend the job after 100 ms and give other jobs their time on the CPU. Once the other jobs have had their equal share (100 ms each), job1 will get another allocation of CPU time and the cycle will repeat. This process continues until the job finishes and needs no more time on the CPU.

Suppose there are two processes running. Both processes are assigned memory pages. CPU is processing process one. Following figure illustrates this scenario.

swap space example

As we can see in above figure, no memory pages available for another process. System will not start new process until any existing process is finished. Swap space can improve this situation a little bit. If swap space is configured and RAM is filled, idle pages will be moved in swap space.

For example, when process A is executing, memory pages occupied by process B will be moved in swap space. Vice versa when process B is executing, memory pages occupied by process A will be moved in swap space. This way by using same physical memory Linux can run more processes with swap space.

The process of moving idle memory pages from RAM to swap is known as page out. The process of moving required memory pages back from swap to RAM in known as page in.

Following figure illustrates this process

linux swap space example

Key points
  • The swap space is the hard disk space which is used to supplement the system RAM by holding idle memory pages.
  • Since swap space resides in hard disk, it is incredibly slow in comparison with RAM.
  • Swap space is the essential part of Linux configuration.
  • If swap space is configured, a threshold value for physical memory will also be configured. The swap space is used only when physical memory is used beyond the threshold.
  • As long as free memory remains below the threshold, no swap space will be used.
  • Swap usage should be monitored closely. If swap starts being used intensively, the performance of system would be decrease.

This tutorial is the fifth part of our article “Linux Disk Management Explained in Easy Language with Examples”. You can read other parts of this article here.

Linux Disk Management Tutorial

This is the first part of this article. This part explains basic concepts of Linux disk management such as BIOS, UEFI, MBR, GPT, SWAP, LVM, RAID, primary partition, extended partition and Linux file system type.

Manage Linux Disk Partition with fdisk Command

This is the second part of this article. This part explains how to create primary, extended and logical partitions from fdisk command in Linux step by step with examples.

Manage Linux Disk Partition with gdisk Command

This is the third part of this article. This part explains how to create GPT (GUID partition table) partitions from gdisk command in Linux step by step with examples.

Linux Disk Management with parted command

This is the fourth part of this article. This part explains how to create primary, extended, logical and GPT partitions from parted command in Linux step by step with examples.

Learn how to configure LVM in Linux step by step

This is the sixth part of this article. This part explains basic concepts of LVM in detail with examples including how to configure and manage LVM in Linux step by step.

How to configure RAID in Linux Step by Step Guide

This is the last part of this article. This part explains basic concepts of RAID in detail with examples including how to configure and manage software RAID in Linux step by step.

How to create swap partition

We can create a new partition or can use free space from existing partition for swap space. We will learn both methods. Let’s start with partition method.

Since swap partition is created as a regular partition, we can use any disk utility from fdisk, gdisk or parted. Second, third and fourth part of this article explains fdisk, gdisk and parted in detail with examples respectively. In this tutorial we will use fdisk utility to create a swap partition.

New partitions can be created only from un-partitioned disk space. For this tutorial I assume that either you have un-partitioned disk space or have a blank disk for practice. For demonstration purpose I added one additional 2GB hard disk (/dev/sdc) in system.

Let’s initiate fdisk command

fdisk dev sdc

Replace /dev/sdc with your disk.

Use p command to get the overview of hard disk.

fdisk commnad p option

The p command provides information about available space in hard disk to create a new partition. If last partition ends before the last sector of hard disk, we have available space to create a new partition. As we can see in above output currently no value is available in partition section which means there is no partition available and entire disk space is available for new partition. Let’s create a 500MiB partition.

Type n and press Enter key.

Type p and press Enter key.

Type the partition number (or keep the default number) and press Enter key.

Type the first available sector for partition (or accept the default sector) and press Enter key.

Type the last available sector for partition. Alternatively we can use KiB, MiB or GiB units to define the size of partition.

Verify the creation of partition with p command

Following figure illustrates above process step by step

fdisk command create new partition

Each partition uses a special marking known as partition system identifier. This marking is used to identify the purpose of partition. To print all available partition types type l and press Enter key.

fdisk list partition type

As we can see in above output value 82 is used as partitions type identifier for swap space.

Unless we change the type of any partition it is marked as Linux Standard default.

To use partition for swap space we have to change the partition type.

Type t and press Enter key

Type 82 and press Enter key

Verify the change with p command

Following figure illustrates above process

fdisk change partition type

The fdisk will not save anything in disk until we confirm the action. To accept the change type w and press Enter key

fdisk save partition table

The fdisk cannot update the in-memory kernel partition table. Run following command to force the kernel to reread the partition table.

partprobe dev sdc

Replace /dev/sdc with your disk name.

We have successfully created swap partition.

Formatting swap partition

We have to format a partition with appropriate file system before it can be used for data storage. File system allows us to create files and directories in partition. Unlike a regular partition which is used to store the user data, the swap partition is used to store the system data.

The mkswap command is used to format a partition for swap space. Since swap partition is never used for user data, this command does not create a file system in partition; it only applies a swap signature in partition. It writes signature in a single block of data, leaving the rest of the partition unformatted. This unformatted space is used to store the memory pages.

Let’s format the partition with mkswap command.

mkswap format command

Now this partition is ready to use for swap space. Before we learn how to update the system about this additional swap space let’s have a quick look on two important commands which are frequently used to view the current status of swap space.

free : - This command display the current status of memory.

swapon –s :- This command display the status of swap space.

free swapon -s command linux

As we can see in above output a partition of 1023996MiB is configured as a swap space. From this space 12596MiB is currently used and 1011400MiB is available.

Activating swap partition

To activate new swap partition following command is used.

# swapon  [device_name]

Here device_name is name of partition or file which we want to use for swap space. Partition or file must be marked with swap signature.

Let’s activate the recently created swap partition.

activate swap partition

As we can see in above output, before activating this swap partition total swap space was 1023996MiB which increased to 1535992MiB after activating this swap partition. This additional 511996MiB swap space came from new swap partition (/dev/sdc1) which can also be verified with swapon –s command. This increased swap space will be available only for this session. After reboot we have to mount this swap partition again. If we want to use this swap partition permanently, we have to make an entry in fstab file. Kernel reads fstab file to mount the file system in boot process.

Mounting swap space permanently

System configuration files should always be backed up before editing. Let’s take the backup of fstab file and open it for editing

fstab file backup

By default this file has entry for those partitions which were created during the installation. To mount any additional partition automatically we have to make an entry for that partition in this file. Each entry in this file has six fields.

default fstab file

Number Filed Description
1 What to mount Device which we want to mount. We can use device name, UUID and label in this filed to represent the device.
2 Where to mount The directory in main Linux File System where we want to mount the device.
3 File system File system type of device.
4 Options We can use supported options here to control the mount process. For this tutorial we will use default options.
5 Dump support To enable the dump on this device use 1. Use 0 to disable the dump.
6 Automatic check Whether this device should be checked while mounting or not. To disable use 0, to enable use 1 (for root partition) or 2 (for all partitions except root partition).

Let’s updated each filed one by one.

What to mount

As we know each resource in file system has a unique ID called UUID. When mounting a partition permanently we should use UUID instead of its name.

The UUID stands for Universally Unique Identifier. It is a 128-bit number, expressed in hexadecimal (base 16) format.

To know the UUID of all partitions we can use blkid command. To know the UUID of a specific partition we have to use its name as argument with this command.

Once we know the UUID, we can use it instead of device name. We can also use copy and paste option to type the UUID.

To use copy and paste operation, open another terminal and run blkid command. Now copy the UUID of partition from second terminal and paste in fstab file which is opened in first terminal. Once we are done close the second terminal.

copy and paste uuid

Where to mount

Since swap partition is used as a hardware device by system, it cannot be mounted in file system which is accessible through the directory structure. Use value swap in this filed as a placeholder value.

File system type

The file system type for swap space is swap.

Mount option

Use default mount option.

Dump support

Since it is used only to store temporary memory pages, disable this option.

Automatic check

Since it does not contain any user or system data, disable this option also.

After updating all fields save the file.

swap partition fstab entry

We can check fstab file entries with mount –a command. This command will mount everything listed in /etc/fstab file. So if we made any mistake while updating this file, we will get an error as the output of this command.

If you get any error as the output of mount –a command, correct that before rebooting the system. If there is no error, reboot the system.

reboot the system

After reboot we can use free and swapon command again to verify that swap partition is mounted correctly.

confirm swap partition

Above output confirms that swap partition is mounted correctly.

Swap space is used only if physical memory consumption extends the threshold. Swap space is used in a series. Swap space series is displayed in Priority filed. First swap space will be used first. Second swap space will be used only if first swap space is filled completely.

Removing swap space partition

Swap space can be removed in following three steps: -

  • Deactivate the swap space
  • Remove entry from fstab file
  • Delete the swap partition

The swapoff command is used to deactivate the swap space. For example following command will be used to deactivate the /dev/sdc1 swap partition

#swapoff /dev/sdc1

We took the backup of /etc/fstab file before starting this practice. We can either restore that file back or can delete swap partition entry from current file.

Following figure illustrates both steps

restore fstab file

Finally delete the partition and update the kernel with following steps: -

  • Run fdisk /dev/sdc command to initiate fdisk utility. [Replace /dev/sdc with your disk name]
  • Use p command to know the partition number
  • Use d command to delete the swap partition. If disk has only one partition, it will be selected automatically. If disk has multiple partitions, provide the correct partition number.
  • Use p command again to confirm that partition is removed
  • Save the change with w command
  • Run partprobe command to update the kernel about this change.

Following figure illustrates above steps

delete swap partition

How to create swap space from file

As we know to create a new swap partition, un-partitioned disk space is required. If we don’t have un-partitioned disk space, we cannot create new swap partition. In that case we can increase swap space from file.

To create swap space from file we first need to create a swap file. Use df –h command to figure out the partition which has enough free space to store the swap file and run following to create swap file in that partition.

#dd if=/dev/zero of=/swap-file count=1000 bs=1M

Let’s understand this command in detail.

dd :- The dd (disk duplicator) command is used to copy or backup the low level data.

if=/dev/zero :- This is the first option. This option accepts source location as argument. In this example I copied from /dev/zero disk file. The /dev/zero is a special file in Linux system which supplies endless zero bytes.

of=/swap-file :- This is the second option. This option accepts destination location as argument. In this example I copied at /swap-file. The swap-file is the name of file. You can use any descriptive name here.

count=1 :- This is the third option. It is used to define the number of block which we want to copy.

bs=1 :- This is the last option. It is used to define the size of block. 1M stands for one megabyte.

Basically this command creates a file of 1GB (1M x 1000 count) from null characters (zero bytes).

Following figure illustrates above process step by step

dd command

We can also verify the size of swap file with du –h command.

du -h command

Since this file is created with null characters for memory pages, we cannot read its content with regular commands.

cat swap file

Usually there is no need to read the file which contains only null characters, but if you are still interested in reading zero bytes, use –v option with cat command or use od command.

od swap file

Now we can use this file for swap space. Let’s put swap signature in this file.

mkswap swap file

Since this file will be used only by system, change its permission to 0600.

change swap file permission

Same swapon command will be used to activate this swap space also.

swapon swap file

From performance point of view, there is no difference between both methods. From security point of view partition method is more secure and stable in comparison with file method. Since swap file is created in user accessible directory structure, it could be moved or deleted. So we should use swap file only if we do not have free disk space to create a swap partition and we have to increase swap space immediately.

Removing swap file

To remove a swap file first deactivate it with swapoff command

swapoff swap file

We can also use free and swapon –s command to confirm the remove operation.

Now use rm –rf command to delete the file

rm -rf swap file

That’s all for this tutorial. In next part we will learn how to create and manage LVM partitions in Linux step by step with examples.

ComputerNetworkingNotes Linux Tutorials How to create swap partition in Linux