Managing Swap Space on Linux
Priyanshu
Posted on October 19, 2024
Managing swap space is essential for system performance, especially when your system is running low on RAM. Here’s a step-by-step guide on how to manage swap space using common Linux commands:
Check Current Swap Usage
~$ swapon
This command lists all active swap partitions and swap files. It helps you understand the current swap usage and its status.
Turn Off All Swap
~$ sudo swapoff -a
This command disables all active swap space. It’s necessary when you want to modify existing swap or create a new swap file. -a applies the command to all swap partitions/files.
Verify RAM and Swap Usage
~$ free -h
This command displays the current usage of RAM and swap space in a human-readable format. It helps you confirm that the swap space has been turned off. It also shows the available memory after disabling swap.
Create a New Swap File
~$ sudo fallocate -l 8G /swapfile
The fallocate command creates a file of a specified size, in this case, an 8 GB file named /swapfile. This file will be used as the swap space.
Set Correct Permissions for the Swap File
~$ sudo chmod 600 /swapfile
This command sets the file permissions to 600, ensuring that only the root user has read and write access to the /swapfile. This is important for security, as it prevents unauthorized access to the swap file.
Mark the File as Swap
~$ sudo mkswap /swapfile
This command sets up the /swapfile as a swap space. It prepares the file for use as swap by formatting it accordingly.
Enable the New Swap Space
~$ sudo swapon /swapfile
This command enables the /swapfile as active swap space, allowing the system to use it when necessary. At this point, the new swap space is ready for use.
Verify the Updated Swap Space
~$ free -h
Running this command again allows you to see the updated RAM and swap usage, confirming that the new swap space has been added and is now active.
Posted on October 19, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.