Sometimes, a computer does not have enough physical RAM to perform all planned operations properly. In these situations, you can borrow memory from disk space, sacrificing access speed: the memory-intensive task will be executed, albeit not as quickly as desired. In many systems, a swap file is created during the installation process. However, virtual servers typically come without virtual memory.
Create a swap file
Use the fallocate
command to allocate space for the swap file.
sudo fallocate -l 4G /swap
This command creates a new file named /swap
with a preallocated size of 4 gigabytes.
Format the swap file
After creating the swap file, you must format it for swap usage. Use the mkswap command to set up a Linux swap area on the file:
sudo mkswap /swap
Set access permissions
Set the appropriate access permissions to ensure only the system can use the swap file. Run the following commands to change the owner and set the permissions:
sudo chown root:root /swap
sudo chmod 0600 /swap
The first command changes the owner and group of the /swap file to root. The second command sets the permissions to 0600, which grants read and write permissions only to the owner (root).
Activate the swap file
To enable the swap file, use the swapon command:
sudo swapon /swap
Configure the system to use the swap file at startup
To ensure that the swap file is activated automatically upon system boot, add an entry to the /etc/fstab file. Open the file with a text editor, such as nano:
sudo nano /etc/fstab
/swap swap swap defaults 0 0
Save the changes and exit the editor. The system will now enable the swap file automatically when it starts up.
Verify the swap file status
To check if the swap file is successfully connected, use the free command with the -m flag, which displays memory usage in megabytes:
free -m
If the swap file is connected and active, you will see its size in the “Swap” row of the output.