How to create a Swap file in Linux

Swap space/partition is space on a disk created for use by the operating system when memory has been fully utilized. It can be used as virtual memory for the system; it can either be a partition or a file on a disk.

Swap space can take the form of either a dedicated swap partition or a swap file. In most cases, when running Linux on a virtual machine, a swap partition is not present, so the only option is to create a swap file

Creating Swap partition in linux :

You can use the following command to create the swap file:

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

Here bs=1024 means read and write up to 1024 bytes at a time

Also we can make use of fallocate command

# fallocate –length 1GiB /swapfile

Provide appropriate permission to file created so that only root user can access

# chmod 600 /swapfile

Now use the mkswap utility to set up the file as Linux swap area:

# mkswap /swapfile

Enable the swap using below command:

# swapon /swapfile

For making the change permanent vi the /etc/fstab file and append the following line

# /swapfile swap swap defaults 0 0

meaning of each field:

swapfile – device/file name

swap – defines device mount point

swap – specifies the file-system type

defaults – describes the mount options

0 – specifies the option to be used by the dump program

0 – specifies the fsck command option

How to check if the swap file was created using the swapon command or free command .

# swapon -–show
# free -h

How to check and adjust the swappiness value

Swappiness is a Linux kernel property that defines how often the system will use the swap space. Swappiness can have a value between 0 and 100. 

Default value is 60

Use below command to check the value of swapniess

# cat /proc/sys/vm/swappiness

To set the swappiness value to 20, you would need run the following sysctl command:

 # sysctl vm.swappiness=20

To make this parameter persistent across reboots append the following line to the /etc/sysctl.conf file

# vm.swappiness=20

 

Check : Ansible Ad-hoc Commands

Leave a Reply

Your email address will not be published. Required fields are marked *