The swap partition is a place where system will keep temporary files so that it can do the processing of data bit faster. Suppose your swap is getting filled and there is no raw partition left for creating swap partition on the server what we can do? At any cost your management asked you to increase the swap to improve the system performance.

To come out of this situation there is one solution provided by Linux e.i we can create a swap file with in all ready existing and using partition if that partition is having sufficient free space

Step 1: Switch off all the swap before any swap related work

#swapoff -a

 Step 2: Determine what is the swap size we required(here i am taking 128 MB) and execute the following command with count equal to 131072 (because 131072 is equal to 128 M) This will create a swap file name swap file in / directory with size of 128 MB.

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

Let me explain above command.

dd is an excellent command which is used to take backups of partitions, create MBR, create empty files etc. Here dd is used to create a empty file called /swapfile by taking input file as /dev/zero with block size as 1024 byts and number of these bytes as 131072. This command will create a file with 128MB.

Step 3: Now set this swap file in order to use this virtual file as swap

#mkswap /swapfile

Step 4: Edit the /etc/fstab file to specify the swap file for saving these settings permanently.

#vi /etc/fstab
/swapfile    swap    defaults    0 0

save and exit the file. Learn about vi editor here

Step 5: Update the kernel about the mount table changes.

#mount -a

Step 6: After all these changes we have to on the swap once again with command as given below.

#swapon -a

Step 7: Check weather the swap space is updated or not by using any one of the following command

#free -m
#swapon -s
#cat /proc/swaps

Ok we are done with creating the swap file, how about removing it?. Follow below procedure to remove the swap file.

Removing swap

Step 1: Before doing any thing with swap first we have to switch off the swap

#swapoff -v /swapfile

Step 2: Remove or comment the line of swap file in /etc/fstab file system configuration file

#vi /etc/fstab
/swapfile    swap    defaults    0 0

then save and exit

Step 3: update the kernel about mount table changes

#mount -a
Step 4: Remove the swapfile permanently
 #rm /swapfile

Please comment your thoughts on this.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.