How to make swapfile in Linux ?

Ravikant Kumar
devopsfunda
Published in
2 min readOct 14, 2017

Swap is a space on a hard drive which is used to store RAM data. Swapfile in linux is basically used to increase storage capacity of RAM. Suppose an application data is stored in RAM but currently not in use and new application need RAM space than older data in RAM is stored in swap space. RAM is faster then swap space so OS will prefer to keep running data in RAM and use swap for older data.

Easy Way to add swapfile

Step 1: Allocate file using fallocate command.

$ sudo fallocate -l 2G /swapfile

Above command create a file name swapfile in /data directory and allocate 2GB space. You can change your directory according to you choice.

Optional: If above command not work then try below one.

$ sudo dd if=/dev/zero of=/swapfile count=2040 bs=1MiB

Suppose you have 1GB RAM than you should use 2GB swap. According to your RAM capacity you need swap file. When you have enough RAM capacity than no need of swap. After enabling swap you should monitor swap space for how much space of ram is using. When little bit of swap space is used in your OS then decrease swap space. No need of swap space when you have enough space.

Step 2: Change mode of created file

$ sudo chmod 600 /swapfile

This command give read and write permission to the swap file

Step 3: Now make this space as a swappable.

$ sudo mkswap /swapfile

Output like: Setting up swapspace version 1, size = 2097148 KiB

no label, UUID=0b37c1a2–733d-4dc6–8302-e581a4a454f2

Step 4: Now enable this swapfile. System start utilizing it after enabling

$ sudo swapon /swapfile

Note : If you have error like “swapon: /swapfile: swapon failed: Invalid argument” then use below command instead of “fallocate command” in first step

$ sudo dd if=/dev/zero of=/swapfile count=2040 bs=1MiB

Now you can verify you swap file by following command

$ sudo swapon --show

NAME TYPE SIZE USED PRIO

/data/swapfile file 2G 0B -1

total used free shared buffers cached

Mem: 1017372 510504 506868 68 32396 404620

-/+ buffers/cache: 73488 943884

Swap: 2097148 0 2097148

Step 5: At last step you can enter details of your swap file in fstab file. So that when you reboot your system than swap is in use. Add below line in fstab.

$ vim /etc/fstab

/swapfile swap swap defaults 0 0

--

--