Nahidul Islam

Mastering SWAP File: How to create, check and delete

Initial Verification of the SWAP Status

Before diving into creating or deleting SWAP files, it’s essential to understand the current status of your system’s SWAP. The htop command is a powerful tool to visualize system resources and check the current SWAP usage.

htop

Creating a SWAP File

To enhance your server’s memory capabilities, follow these steps to create a SWAP file:

Allocate Space: Use the fallocate command to create a 2-gigabyte SWAP file. Adjust the size based on your server’s memory needs, aiming for at least double the server memory.

sudo fallocate -l 2G /swapfile

Set Permissions: Ensure only the root user can read and write to the SWAP file.

sudo chmod 600 /swapfile

Format as SWAP: Utilize the mkswap utility to set up the file as Linux swap area.

sudo mkswap /swapfile

Activate SWAP: Enable the SWAP file to make it immediately available.

sudo swapon /swapfile

Verify Status: Confirm the changes using htop.

htop

Make Changes Permanent: Open /etc/fstab and add an entry to ensure the SWAP file persists after a server reboot.

sudo nano /etc/fstab

Add the line:

/swapfile swap swap defaults 0 0

Reboot Server: Reboot the server to apply changes permanently.

sudo reboot

Verify After Reboot: Ensure the SWAP file is active post-reboot using htop.

Swappiness & Linux Cache Pressure

Optimize your system’s performance by adjusting swappiness and cache pressure:

Edit sysctl.conf: Open the sysctl.conf file.

sudo nano /etc/sysctl.conf

Add Configurations: Append the following lines at the end of the file.

vm.swappiness = 1
vm.vfs_cache_pressure=50

Apply Changes: Enable the new configurations.

sudo sysctl -p

Removing a SWAP File

If you need to reclaim space, follow these steps to remove a SWAP file:

Deactivate SWAP: Turn off the SWAP file.

sudo swapoff -v /swapfile

Edit fstab: Open /etc/fstab using nano.

sudo nano /etc/fstab

Remove Entry: Delete the SWAP file entry from the file.

/swapfile swap swap defaults 0 0

Delete SWAP File: Remove the SWAP file.

sudo rm /swapfile

Reboot the server to finalize changes.

By following these detailed steps, you can confidently manage SWAP files on your Linux server, optimizing performance and resource utilization.

Open chat
1
Send me a Message
Hello, How can i help you?