Skip to content

Instantly share code, notes, and snippets.

@memandip
Last active November 10, 2022 08:35
Show Gist options
  • Save memandip/46a93649d83900631abade40f6ae1ab8 to your computer and use it in GitHub Desktop.
Save memandip/46a93649d83900631abade40f6ae1ab8 to your computer and use it in GitHub Desktop.
create or update swap ubuntu
If swapfile already exists
sudo swapoff -a
sudo fallocate -l 2G /swapfile
If the fallocate utility is not present on your system, or you get an error message saying fallocate failed: Operation not supported, use the following command to create the swap file:
sudo dd if=/dev/zero of=/swapfile bs=1024 count=2097152 (2 * 1024 * 1024)
Set the file permissions to 600 to prevent regular users to write and read the file:
sudo chmod 600 /swapfile
Create a Linux swap area on the file:
sudo mkswap /swapfile
Setting up swapspace version 1, size = 2 GiB (2147479552 bytes)
no label, UUID=fde7d2c8-06ea-400a-9027-fd731d8ab4c8
Activate the swap file by running the following command:
sudo swapon /swapfile
To make the change permanent open the /etc/fstab file:
sudo nano /etc/fstab
and paste the following line:
/etc/fstab
/swapfile swap swap defaults 0 0
Verify that the swap is active by using either the swapon or the free command, as shown below:
sudo swapon --show
NAME TYPE SIZE USED PRIO
/swapfile file 2G 0B -1
sudo free -h
Adjusting the Swappiness Value
Swappiness is a Linux kernel property that defines how often the system will use the swap space. It can have a value between 0 and 100. A low value will make the kernel to try to avoid swapping whenever possible, while a higher value will make the kernel to use the swap space more aggressively.
On Ubuntu, the default swappiness value is set to 60. You can check the current value by typing the following command:
cat /proc/sys/vm/swappiness
60
While the swappiness value of 60 is OK for most Linux systems, for production servers, you may need to set a lower value.
For example, to set the swappiness value to 10, run:
sudo sysctl vm.swappiness=10
To make this parameter persistent across reboots, append the following line to the /etc/sysctl.conf file:
/etc/sysctl.conf
vm.swappiness=10
The optimal swappiness value depends on your system workload and how the memory is being used. You should adjust this parameter in small increments to find an optimal value.
Removing a Swap File
To deactivate and delete the swap file, follow these steps:
First, deactivate the swap space:
sudo swapoff -v /swapfile
Next, remove the swap file entry /swapfile swap swap defaults 0 0 from the /etc/fstab file.
Finally, remove the actual swapfile file using the rm command:
sudo rm /swapfile
ref link: https://linuxize.com/post/how-to-add-swap-space-on-ubuntu-20-04/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment