How to increase swap by creating a file in Linux ?

Today in this article, we will see how to increase the swap on our Linux system by creating a flat file on some filesystem.

The advantage of creating swap this way is that we can remove the swap anytime from the server.

I. Create a file which will be used as swap.

[user@ngelinux01 /oracle]$ sudo fallocate -l 4194304K /oracle/swapfile
[sudo] password for user:
[user@ngelinux01 /oracle]$

Or, the better way to do this is via dd command as fallocate command can put holes instead of zeros and swap can give error.

bash-4.2$ sudo dd if=/dev/zero of=/oracle/swapfile bs=1M count=4100 status=progress
Apr 21 05:47:42 ngelinux01 sudo: user : TTY=pts/5 ; PWD=/oracle ; USER=root ; COMMAND=/usr/bin/dd if=/dev/zero of=/oracle/swapfile bs=1M count=4100 status=progress
3381657600 bytes (3.4 GB) copied, 4.001839 s, 845 MB/s
4100+0 records in
4100+0 records out
4299161600 bytes (4.3 GB) copied, 4.84931 s, 887 MB/s


II. Check the new file of around 4Gb created.

[user@ngelinux01 /oracle]$ ls -ltr
total 4194304
drwxr-xr-x 2 root root          6 Mar  7 15:02 crash
-rw-r--r-- 1 root root 4294967296 Apr 21 05:27 swapfile


III. Change the swap file permissions

[user@ngelinux01 /oracle]$ sudo chmod 600 swapfile
[user@ngelinux01 /oracle]$ ls -l /oracle/swapfile
-rw------- 1 root root 4294967296 Apr 21 05:27 /oracle/swapfile
[user@ngelinux01 /oracle]$


IV. Make the file swap area.

[user@ngelinux01 /oracle]$ sudo mkswap /oracle/swapfile
Setting up swapspace version 1, size = 4194300 KiB
no label, UUID=8fe02381-328b-427b-9dcb-e833d861eacd
[user@ngelinux01 /oracle]$


V. Make it permanent by putting it in fstab file.

# cat /etc/fstab | grep -i swapfile
/oracle/swapfile                         swap                    swap    defaults        0 0


VI. Turn on the swap.

bash-4.2$ sudo swapon -a
Apr 21 05:51:14 ngelinux01 sudo: user : TTY=pts/5 ; PWD=/var/log ; USER=root ; COMMAND=/usr/sbin/swapon -a
Apr 21 05:51:14 ngelinux01 kernel: Adding 4198396k swap on /oracle/swapfile. Priority:-2 extents:2 across:4328472k FS
0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments