Change swap size in Ubuntu
Starting with Ubuntu 17.04, the swap
partition is replaced with a swap
file, which makes it easy to be resized.
NOTE: Most of the commands below will require root privilege.
You can check your current swap size with
swapon -s
or
free -h
By default, the swapfile is /swapfile
with file mode 600
and it belongs to the root
user.
ls -lh /swapfile
If you want to resize your swapfile, it’s simple. The steps are
-
Disable the current swap file:
swapoff -a
-
Change the size of the swap file. There are two possible ways, you can choose either of them
-
Use the command
dd
dd if=/dev/zero of=/swapfile bs=1M count=4096
This will allocate
4GB
in total(each block is1MB
and there are4096
blocks) to/swapfile
. -
Use the command
fallocate
fallocate -l 4G /swapfile
This will also allocate
4GB
to/swapfile
.
-
-
Make sure the file mode is
600
bychmod 600 /swapfile
The output of
ls -lh /swapfile
should be like-rw------- 1 root root 4G May 23 19:48 /swapfile
-
Make the newly created swap file useable by
mkswap /swapfile
-
Activate the swap file
swapon /swapfile
-
Add swap setting to your
/etc/fstab
by adding(if this line does not exist) this line/swapfile none swap sw 0 0
If you want to disable the swap file in your system, it’s also very simple.
-
Disable the swap
swapoff -v /swapfile
-
Delete(or comment) the swap line in
/etc/fstab
/swapfile none swap sw 0 0
-
Remove the actual swap file
rm -v /swapfile