Subscribe to our RSS feed to get alerted every time SUBSCRIBE!

How to Create Linux Swap Drive using Swap File on Ubuntu / AlmaLinux / Rocky Linux

Have you missed to make SWAP drive during installation on Enterprise Linux. This tutorial makes a file as a your SWAP drive by using some commands where we can make the SWAP drive and add this drive to the respective boot and service managers.

Step-1 (Switch to root user accounts)
 su -
Step-2 (Allocate Space for a Swap file)

Note: SWAP drive is double of your RAM Size. If you have 2GB of RAM then Size of SWAP drive is 4GB. Here you can change or assign the 2G to your respective SWAP drive sizes.

 fallocate -l 2G /mnt/swapfile.swap
Step-3(Create a Swap file)

Note: Here we are using 2GB hence 2048 in the terms of MB you can change the value.  This given command requires some time depending upon the size of disk and CPU. Hence please be a patience during this command.

 dd if=/dev/zero of=/mnt/swapfile.swap bs=2048 count=1048576

Sample Output

1048576+0 records in
1048576+0 records out
2147483648 bytes (2.1 GB) copied, 49.4045 s, 43.5 MB/s
Step-4 (Format the Swap file)
 mkswap /mnt/swapfile.swap

Sample Output

Setting up swapspace version 1, size = 2 GiB (2147483648 bytes)
no label, UUID=6f6a8a10-f2ae-4256-9a5c-7084cd0697e1
Step-5 (Enable the Swap file)
 swapon /mnt/swapfile.swap

Sample Output

swapon: /mnt/2GB.swap: insecure permissions 0644, 0600 suggested.
Step-6 (Provide file permissions to swap file)

Note: This is optional command if you use the swap space in production environment you must use the 600 or 644 permissions to the swap file.

 chmod 600 /mnt/swapfile.swap
Step-7 (Add swap file to the boot manager)
 vim /etc/fstab

Add the given commands to last line

 Created by anaconda on Fri Sep 4 06:44:00 2015

 Accessible filesystems, by reference, are maintained under '/dev/disk'
 See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info

UUID=d1b5c2e9-d304-40c1-9ab5-a00ce2ab5450 / ext4 defaults 1 1
/mnt/swapfile.swap none swap sw 0 0

:wq for save and exit

Step-8 (Add swappiness to systemd boot manager)
 vim /etc/sysctl.conf

Note: Here in the place of the swappiness=60 you can put from value 10 and greater value in this type we are using the default value is 60.

Add the given commands to last line

 sysctl settings are defined through files in
 /usr/lib/sysctl.d/, /run/sysctl.d/, and /etc/sysctl.d/.

 Vendors settings live in /usr/lib/sysctl.d/.
 To override a whole file, create a new file with the same in
 /etc/sysctl.d/ and put new settings there. To override
 only specific settings, add a file with a lexically later
 name in /etc/sysctl.d/ and put new settings there.

 For more information, see sysctl.conf(5) and sysctl.d(5).
kernel.sysrq = 1

:wq for save and exit

Check the Swapon Status and restart the PC / Server

 swapon -s
 systemctl reboot

Congratulations now you have created the Linux swap drive using the swap file on Enterprise Linux.