How to Add Swap Space on Rocky Linux 9

Swap space is used when the system's physical memory (RAM) is full, providing additional virtual memory by utilizing disk space. Follow this guide to add a swap file as swap space on a Rocky Linux 9 system.


Check Current Swap Space

To check the existing swap space on your system, run the following command:

sudo swapon --show

Output:

NAME      TYPE      SIZE   USED   PRIO
# No output indicates no swap space is configured

To verify memory and swap details:

free -h

Output:

              total        used        free      shared  buff/cache   available
Mem:           2.0G        1.2G        512M         20M        256M        700M
Swap:            0B          0B          0B

Create a Swap File

To create a swap file with a size of 2GB (adjust the size as needed), use the following command:

sudo fallocate -l 2G /swapfile

If fallocate is not available, use:

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048

Set the correct permissions for the swap file:

sudo chmod 600 /swapfile

Set Up the Swap File

Now, format the file as swap space:

sudo mkswap /swapfile

Output:

Setting up swapspace version 1, size = 2 GiB (2147483648 bytes)
no label, UUID=abcdefgh-ijkl-mnop-qrst-uvwxyz123456

Enable the swap file:

sudo swapon /swapfile

To verify that the swap space is active, run:

sudo swapon --show

Output:

NAME      TYPE      SIZE   USED   PRIO
/swapfile file      2G     0B     -2

Make the Swap File Permanent

Edit the /etc/fstab file to ensure the swap file is enabled at boot:

sudo nano /etc/fstab

Add the following line to the file:

/swapfile none swap sw 0 0

Save and exit the editor (Ctrl+O, Enter, Ctrl+X).


Adjust Swap Settings (Optional)

Modify the swappiness value to control the frequency of swap usage:

sudo sysctl vm.swappiness=10

To make this change permanent, add the following line to /etc/sysctl.conf:

vm.swappiness=10

Reload the settings:

sudo sysctl -p

Verify Swap Configuration

Confirm that the swap file is active and permanent by running the following commands:

sudo swapon --show
cat /proc/swaps
free -h

Output:

NAME      TYPE      SIZE   USED   PRIO
/swapfile file      2G     0B     -2

              total        used        free      shared  buff/cache   available
Mem:           2.0G        1.2G        512M         20M        256M        700M
Swap:          2.0G          0B        2.0G

Conclusion

You have successfully added and configured swap space on Rocky Linux 9. The swap file will now be used as virtual memory whenever physical memory runs low, ensuring smoother system performance.


CrownCloud - Get a SSD powered KVM VPS at $4.5/month!
Use the code WELCOME for 10% off!

1 GB RAM / 25 GB SSD / 1 CPU Core / 1 TB Bandwidth per month

Available Locations: LAX | MIA | ATL | FRA | AMS