How to increase swap file size
We had a couple of servers running whose swap files needed to be increased. These are the steps I took to add more swap space.
Let’s start by checking where our current swap file is located and how big it is:
swapon -s
Its output will look something like this:
Filename Type Size Used Priority
/mnt/swap.1 file 524288 0 -1
Our swap file is located at /mnt/swap.1
and is currently 512M big. Before we continue, let’s disable all swap files:
swapoff -a
Now we overwrite the existing swap file to increase its size with the dd
command. In this example, I’m creating a file that is 1GB in size (1048576 blocks of 1024 bytes):
dd if=/dev/zero of=/mnt/swap.1 bs=1024 count=1048576
An alternative to the dd
command is fallocate
, which is a lot faster since it only preallocates the space on the file system instead of writing zeroes into it. The command looks like this:
fallocate -l 1G /mnt/swap.1
Note: fallocate
is not suitable for every file system, as pointed out in the swapon Ubuntu man pages so make sure it will work properly on your system:
You should not use swapon on a file with holes. This can be seen in the system log as
swapon: swapfile has holes.
The swap file implementation in the kernel expects to be able to write to the file directly, without the assistance of the filesystem. This is a problem on preallocated files (e.g. fallocate(1)) on filesystems like XFS or ext4, and on copy-on-write filesystems like btrfs.
Let’s continue by setting up the file as a swap file:
mkswap /mnt/swap.1
And now tell the system to start swapping to it:
swapon /mnt/swap.1
That’s it! We can verify that the new swap file is being used using the free
command:
free -m
You should see the “Swap:” line at the end of its output:
total used free shared buffers cached
Mem: 988 854 134 62 12 210
-/+ buffers/cache: 631 356
Swap: 1023 0 1023