How to Add Swap Space on Ubuntu 24.04
This guide is applicable only for KVM-based VPSes and dedicated servers, If you wish to increase swap on your OpenVZ-based VPS please contact us via a Support ticket from the client area.
Swap space, also known as "swap," is a reserved area on a server's storage device that the operating system can use as virtual memory when allocated memory is fully utilized. When your server's memory is exhausted due to running applications and processes, the operating system moves less frequently used data from memory to the swap space. This frees up memory for more active tasks and helps prevent the system from slowing down or crashing due to memory exhaustion.
Here's how to add swap space on an Ubuntu 24.04 server:
Check Swap Information
Command to check swap size.
swapon --show
Output:
root@vps:~# swapon --show
NAME TYPE SIZE USED PRIO
/swap.img file 2.4G 0B -2
root@vps:~#
Or you can check using the free
command.
free -m
Output:
root@vps:~# free -m
total used free shared buff/cache available
Mem: 3916 433 2899 1 812 3483
Swap: 2420 0 2420
root@vps:~#
NOTE: If the output is empty, it means that swap space is not enabled yet on your system.
Add Swap
Command to create a Swap file.
NOTE: We are adding 1GB if you want to add a different size then you can replace it in place of 1G
fallocate -l 1G /swapfile
or
dd if=/dev/zero of=/swapfile bs=1024 count=1048576
To set write permission.[Default permissions only enable for root user]
chmod 600 /swapfile
To set up a swap area on the file.
mkswap /swapfile
Output:
root@vps:~# mkswap /swapfile
Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
no label, UUID=cfae2d65-66dc-4233-8a6f-bd0ab841a250
root@vps:~#
To activate the swap file.
swapon /swapfile
Open the following file and add the given content to change it to permanent.
nano /etc/fstab
Add the following line.
/swapfile swap swap defaults 0 0
Now check the swap size.
swapon --show
or
free -m
Output:
NAME TYPE SIZE USED PRIO
/swap.img file 2.4G 0B -2
/swapfile file 1024M 0B -3
root@vps:~#
Or
root@vps:~# root@vps:~# free -m
total used free shared buff/cache available
Mem: 3916 425 1868 1 1866 3490
Swap: 3444 0 3444
root@vps:~#
NOTE: Now the added swap space can be seen.
Remove Swap
Deactivate the swap space.
swapoff -v /swapfile
Output:
root@vps:~# swapoff -v /swapfile
swapoff /swapfile
root@vps:~#
Next, remove the following line from the file /etc/fstab
nano /etc/fstab
/swapfile swap swap defaults 0 0
Command to remove the file.
rm /swapfile
This concludes our topic of configuring swap in Ubuntu 24.04
If you can not configure and face technical difficulties, kindly reach out to us via Support Ticket.
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