Create extra swap file

You added RAM after a while and now swap space isn’t enough ? You can add more space to it.

The rule is simple, old and sometimes a few people disagree: Swap = RAM + 25%. Anyway. Let’s see how to add a new swap file.

Need root so:


Create a swap file command

Type the following command to create a 1GB swap file

dd if=/dev/zero of=/swapfile bs=1G count=1

Need more or less ? Just change the 1G with the GB you want for swapfile.

Sample output:


root@virgo [/]# dd if=/dev/zero of=/swapfile bs=1G count=1
1+0 records in
1+0 records out
1073741824 bytes (1.1 GB) copied, 0.742201 s, 1.4 GB/s
root@virgo [/]# ls -lah swapfile
-rw-r–r– 1 root root 1.0G Nov 25 15:00 swapfile
root@virgo [/]#


Secure the swap file

Type the following chmod command and chown command to secure and set correct file permission for security reasons:
chown root:root /swapfile
chmod 0600 /swapfile



Turn on the swap file

First, use the mkswap command as follows to enable the swap space on Ubuntu:

mkswap /swapfile
Sample outputs:

Finally, activate the swap file, enter:
[code]swapon /swapfile[/code]

Verify new swap file and settings on Ubuntu

Type the following command
[code]swapon -s[/code]
Sample outputs:

Update /etc/fstab file

You need to make sure the swap file enabled when server comes on line after the reboot. Edit /etc/fstab file, enter:
nano /etc/fstab

Append the following line:

Tuning the swap file i.e. tuning virtual memory

You can tune the following two settings:

  1. swappiness
  2. min_free_kbytes
  3. vfs_cache_pressure

How do I set swappiness on a Ubuntu server?

The syntax is:
# sysctl vm.swappiness=VALUE
# sysctl vm.swappiness=20

# echo VALUE > /proc/sys/vm/swappiness
# echo 30 > /proc/sys/vm/swappiness

The value in /proc/sys/vm/swappiness file controls how aggressively the kernel will swap memory pages. Higher values increase agressiveness, lower values descrease aggressiveness. The default value is 60. To make changes permanent add the following line to/etc/sysctl.conf:

For database server such as Oracle or MySQL I suggest you set a swappiness value of 10. For more information see the official Linux kernel virtual memory settings page.