Adding Swap on Ubuntu
Introduction
What Is Swap
Swap in a Linux system, also known as swap space, is similar to the virtual memory (pagefile.sys) of Windows. When memory runs low, a portion of the disk space is turned into virtual memory to store data that is not being used at the moment.
Setup
Check the current state
1
free -m
1
2
3
4total used free shared buffers cached
Mem: 3952 2035 1916 9 217 1392
-/+ buffers/cache: 425 3526
Swap: 0 0 0As you can see, Swap is not enabled. Below we will increase it to match the memory size (4G).
Create the Swap file
1
2
3
4
5
6
7
8mkdir swap
cd swap
sudo dd if=/dev/zero of=swapfile bs=1024 count=4M # bs is the block size, count is the number of blocks; 1024 * 4M = 4G
# 4194304+0 records in
# 4194304+0 records out
# 4294967296 bytes (4.3 GB) copied, 88.3999 s, 48.6 MB/sConvert the file into a swap file.
1
2
3sudo mkswap -f swapfile
# Setting up swapspace version 1, size = 4194300 KiB
# no label, UUID=bebbcbad-dda2-49f9-9aab-4b24b1d62d87Activate Swap
1
sudo swapon swapfile
Verify the activation.
1
free -m
1
2
3
4total used free shared buffers cached
Mem: 3952 3842 109 9 1 3369
-/+ buffers/cache: 470 3481
Swap: 4095 0 4095Configuration
Adjust swappiness
swappiness is a value from 0 to 100. A higher value means the system will more actively use Swap.- Temporary change
1
sudo sysctl vm.swappiness=40
- Permanent change
1
2
3sudo vim /etc/sysctl.conf
# Add a line
vm.swappiness = 40
- Temporary change
Change permissions
Set the file so that only the root user has read and write permissions.1
2sudo chown root:root /swap/swapfile
sudo chmod 0600 /swap/swapfile
Enable on boot
1
sudo vim /etc/fstab
Add the following line at the end of the file.
1
/swap/swapfile none swap sw 0 0