How to expand swap space by using swap file on Linux system

Time:2021-4-13

Imagine a scenario when our Linux system runs out of swap space. In this case, we want to use swap partition to expand swap space, but in some cases, there is no free partition available on the disk, so we can’t expand it.

Therefore, in this case, we can use the swap file to increase the swap space.

Here’s how to extend swap space on linux using swap files
Let’s first check the size of the existing swap space / partition, using the command ‘free – M’ or ‘swap on – s’

My switch partition size is 2 GB, we will expand the switch space to 1GB.

Step 1: use the following DD command to create a 1GB exchange file

Copy code

The code is as follows:

[[email protected] ~]# dd if=/dev/zero of=/swap_file bs=1G count=1
1+0 records in
1+0 records out
1073741824 bytes (1.1 GB) copied, 414.898 s, 2.6 MB/s
[[email protected] ~]#

Replace ‘BS’ and’ count ‘according to your needs

Step 2: set the exchange file permission to 600

Copy code

The code is as follows:

[[email protected] ~]# chmod 600 /swap_file

Step 3: open swap with file_ file)
Use mkswap command to open switch area

Copy code

The code is as follows:

[[email protected] ~]# mkswap /swap_file
Setting up swapspace version 1, size = 1048572 KiB
no label, UUID=f7b3ae59-c09a-4dc2-ba4d-c02abb7db33b
[[email protected] ~]#

Step 4: add an exchange file entry to the fstab file
Add the following entry to the fstab file so that the exchange files can continue to be used after each restart

Copy code

The code is as follows:

/swap_file swap swap defaults 0 0


Step 5: use the command “mkswap on” to enable the exchange file

Copy code

The code is as follows:

[[email protected] ~]# swapon /swap_file
[[email protected] ~]#

Step 6: now look at the swap space

Note: to avoid unexpected situations, use the swapoff command to close it as shown below. Only when you need to use it, use the swapon command shown in step 5 to re enable the swap file.

Copy code

The code is as follows:

[[email protected] ~]# swapoff /swap_file
[[email protected] ~]#

Recommended Today

Quickly use the latest 15 common APIs of vue3

Before that, I wrote a blog to introduce the new features of vue3. I had a brief understanding of the features of vue3, and at the end of the article, I gave you a little experience in vue3Compsition APISimple use of Address of last article: follow Youda’s steps and experience the new features of vue3 […]