Introduction
How do I increase the size of swap file without removing it in the terminal? Is there a way to increase my existing swap file without having to destroy and re-create it or would like to up my swap space from 1GB to 5GB. To solve those issues just follow the instruction described below. And of course, you can also have 2 swap files.
Warning: Flash RAM cells used in SSDs drives have a limited lifespan. Using SWAP files on such devices can lead to issues with hardware degradation over time, faster wear of memory cells and critical hardware failures.
What is Swap?
Swap is an amount of hard drive storage used as operating system memory to temporarily store data that don't have enough room in available operative memory.
Step 1 – Prepare
Before start, need to check where Swap File is located and is there enough disk space for size increase.
df -h
With first command "swapon --show" we can check the location of swapfile, size and usage also priority
with second "df -h" - free disk space on a hard drive that we can allocate for swap file size increase
Step 2 – Turn Off Swap
Before actual swap file increasing, we need to turn off usage of swap file. Be aware that operating system can experience performance drop during this stage.
This moves stuff in swap to the main memory and might take several minutes.
Disable swap file.
Step 3 – Resize the Swap File
Now we are ready to increase the size of swap file.
Adjust the file size, for example, let's set it to 5GB.
The above command will append 1GiB of zero bytes at the end of your swap file.
dd = block read command, to read a block of input and process it, after write it into an output file.
bs=1M specifies a block size of 1MB.
count=4096 specifies the number of blocks (5GB).
Step 4 – Enable back the Swap File
After successful size increase, next step be - turning again swap file on, formatting and refreshing file access permissions.
sudo mkswap /swapfile
sudo swapon /swapfile
Setup the file as a "swap file":
chmod - put again read only file permissions
mkswap - format again enlarged swap file
swapon - enable new swap file
Step 5 – Configuration & Verify
Now, after all those steps are completed your swap file is resized and the configuration is refreshed.
Next correct step be - verify our new swap file and see the if it's used.
free -h
swapon - show swap file
free - show information about hard drive disks usage
Conclusion
This guide will give you a complete instruction of increasing a swap file, reactivation on your Ubuntu 22.04 system, to protect against out-of-memory issues and save time for a migration/upgrade to more powerful system.
Bear in mind, that swap file is last stand option, and can lead to server performance decline as disk IO operations are significantly slower than ones kept in RAM, so the best solution is to optimize your applications or upgrade your server.