opened image

How to Add Swap Swap Partition in OS Linux

In Linux, the SWAP partition plays an important role by providing additional memory for the operating system. If you need to add a new SWAP swap partition to your Linux server, you can use the dd command to get the job done.

Locate the swap partition SWAP

Before creating a new SWAP swap partition, you need to determine the location where you want to install it. Typically, the SWAP swap partition is located in free space on the hard disk or on a separate partition.

You can check the free space on your hard drive with the command:
 

df-h



Create a new swap file

To create a new swap file that will be used as the SWAP swap partition, run the following command:

 

 

 

fallocate -l 1G /swapfile

 



This command creates a file size of 1GB.

Now it needs to be activated:

 

 

 

 

mkswap /swapfile

 



You can enable SWAP with the command:

 

 

 

 

swapon /swapfile

 


To make sure it's enabled, type:

 

 

 

 

swapon --show

 



Change the permissions on the swap file

After creating a new swap file, you need to change the permissions on it using the chmod command:

 

 

 

 

chmod 600 /swapfile

 


This ensures that only root can read and write to the swap file.


At the moment SWAP is not persistent, if you reboot your linux the swap space will not be mounted. To make it permanent, you must add an entry to /etc/fstab.

 

 

 

 

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

 



Now, the next time you boot, SWAP will be available.

If this utility failed to create a swap partition, you can use the dd utility.

 

 

 

 

Create a SWAP swap partition using the dd command


For example, to create a 1 GB swap file with a data block size of 1024 bytes and a block count of 1048576, run the following command:

 

 

 

 

 

 

dd if=/dev/zero of=/swapfile bs=1024 count=1048576

 



After creating a new swap file, you need to change the permissions on it using the chmod command:

 

 

 

 

chmod 600 /swapfile

 



Create a swap partition

After running the dd command, you can create a SWAP swap partition using the mkswap command:

 

 

 

 

mkswap /swapfile

 



Enable Swap Partition

After creating the swap partition SWAP, you can enable it using the swapon command:

 

 

 

 

swapon /swapfile

 



To check that the SWAP swap partition is working, run the swapon -s command:

 

 

 

 

swapon -s

 



This command will list all active SWAP swap partitions on the server, including the new SWAP swap partition you just created.

To add a swap partition to a SWAP created with the dd command, you can use the following command:

 

 

 

 

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

 


Now, the next time you boot, SWAP will be available.

As you can see, adding a new SWAP swap partition on Linux using the dd and fallocate command is a fairly simple process that can be completed in a few steps.