- Advertisement -
VPS House Servers
VPS House Servers
VPS House Servers

In this article, we will explain swap space, and learn how to create swap space using a swap file in Linux: this is important in case we don’t have a swap partition created on the hard disk.

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.

When the kernel runs out of memory, it can move idle/inactive processes into swap creating room for active processes in the working memory. This is memory management that involves swapping sections of memory to and from virtual memory.

With that said, below are the steps we can follow to create a swap space using a file.

How to Create and Enable Swap in Linux

1. In this example, we will create a swap file of size 2GB using the dd command as follows. Note that bs=1024 means read and write up to 1024 bytes at a time and count = (1024 x 2048)MB size of the file.

Alternatively, use the fallocate command as follows.

- Advertisement -
VPS House Cloud Servers
VPS House Cloud Servers
VPS House Cloud Servers

And then set the appropriate permissions on the file; make it readable only by root user as follows.

2. Now setup the file for swap space with the mkwap command.

3. Next, enable the swap file and add it to the system as a swap file.

4. Afterwards, enable the swap file to be mounted at boot time. Edit the /etc/fstab file and add the following line in it.

In the line above, each field means:

  • /mnt/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

6. To set how often the swap file can be used by the kernel, open the /etc/sysctl.conf file and add the line below.

Note that the default value of how frequent swap space can be used is 60 (maximum value is 100). The higher the number, the more frequent swap space utilization by the kernel. When the value is set to 0, the swap file will only be used if the operating system has fully utilized memory.

7. Now verify the swap file was created using the swapon command.

We can optionally reboot the system to effect the above changes using the following command.

Enjoy!

- Advertisement -

There are no comments yet

  • Hello, guest