Ubuntu Linux Create and Add Swap File Tutorial

I‘m a new Ubuntu Linux LTS user. I need additional swap space to improve my Ubuntu server performance. How can I add a swap space on Ubuntu Linux 14.04/16.04/18.04/20.04 LTS using command line over the ssh based session?

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements Ubuntu Linux
Est. reading time 10m
Swap space is nothing but a disk storage used to increase the amount of memory available on the Ubuntu Linux server. In this tutorial, you will learn how to create and use a swap file on an Ubuntu Linux server.

What is a swap file on Ubuntu server or desktop system?

As a sysadmin it is necessary to add more swap space after installation on the server. Swap file allows Ubuntu Linux to use hard disk to increase virtual memory.
Ubuntu Linux Create and Add Swap File Tutorial

Virtual Memory = RAM + Swap space/file

Virtual Memory (1GB) = Actual RAM (512MB) + Swap space/file (512MB)

When the Ubuntu server runs low on memory, it swaps a section of RAM (say an idle program like foo) onto the hard disk (swap space) to free up memory for other programs. Then when you need that program (say foo again), kernel swapped out foo program, it changes places with another program in RAM.

Procedure to add a swap file on a Ubuntu Linux

Open the Terminal app or use the ssh client to get into the remote server. Login as a root user using sudo command:
sudo -s

Create a swap file command

Type the following command to create a 2GB swap file on Ubuntu:
# dd if=/dev/zero of=/swapfile bs=1G count=2
Sample outputs:

2+0 records in
2+0 records out
2147483648 bytes (2.1 GB) copied, 20.2256 s, 106 MB/s

Verify that file has been created on the server:
# ls -lh /swapfile
Sample outputs:

-rw-r--r-- 1 root root 2.0G Oct 29 14:07 /swapfile

Creating swap space using fallocate command instead of dd command

WARNING: Do not use the fallocate(1) command as it does not physically allocate the space, but swapon syscall requires a real space. The following example is for demo purposes and should be avoided at all costs.

Instead of the dd command, you can use the the faster fallocate command to create swap file as follows:
# fallocate -l 1G /swapfile-1
# ls -lh /swapfile-1

Sample outputs:

-rw-r--r-- 1 root root 1.0G Oct 29 14:11 /swapfile-1

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
# ls -lh /swapfile

Sample outputs:

-rw------- 1 root root 2.0G Oct 29 14:07 /swapfile

A world-readable swap file is a huge local vulnerability. The above commands make sure only root user can read and write to the file.

Turn on the swap file

First, use the mkswap command as follows to enable the swap space on Ubuntu:
# mkswap /swapfile
Sample outputs:

Setting up swapspace version 1, size = 2097148 KiB
no label, UUID=10231c61-6e55-4dd3-8324-9e2a892e7137

Finally, activate the swap file, enter:
# swapon /swapfile

Verify new swap file and settings on Ubuntu

Type the following command
# swapon -s
Sample outputs:

Filename				Type		Size	Used	Priority
/dev/sda5                               partition	3998716	704	-1
/swapfile                               file		2097148	0	-2

You can also run the following commands to verify swap file and its usage:
# grep -i --color swap /proc/meminfo
# top
# htop
# atop

How can I disable swapfile on Ubuntu?

You need to use the swapoff command as follows:
# swapoff /swapfile
# swapon -s

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:
# vi /etc/fstab
Append the following line:

/swapfile none            swap    sw              0       0

Save and close the file.

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:

echo 'vm.swappiness=30' >> /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.


You learned how to add swap file under Ubuntu Linux. See the following resources:

This entry is 3 of 7 in the Linux and UNIX Swap File Management Tutorial series. Keep reading the rest of the series:
  1. Linux Add a Swap File
  2. FreeBSD Add a Swap File
  3. Ubuntu Create and add a swap file
  4. Check Swap Usage Size and Utilization in Linux
  5. Linux Find Out What Process Are Using Swap Space
  6. Move swap space from one location to another location
  7. Solaris add a new swap file for database

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 12 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersncdu pydf
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
12 comments… add one
  • vonskippy Oct 30, 2014 @ 0:53

    Adding swap space is almost ALWAYS a bad idea. If your server is hitting swap, it means your applications are poorly configured. Either fix the app config, or add more RAM. There is no way that adding swap will increase performance – even a SSD hard drive is super slow compared to RAM.

  • Jeremy Boden Oct 30, 2014 @ 2:04

    But SOME swap may allow you time to kill a rogue program. It’s also much cheaper than buying RAM.

  • my2cents Oct 30, 2014 @ 2:42

    Nah ALWAYS a bad idea! Ass ram to your physical or virtual server! there’s no way adding swap is a good idea! swap is an idea of the last century where memory costed a lot! ;-)

  • my2cents Oct 30, 2014 @ 2:43

    LOL sorry .. ADD ram to your physical… (sorry about that please moderator correct! thx ) ;-)

  • Magesh M Oct 30, 2014 @ 5:34

    Its good idea to solve our issue instantly but Adding physical RAM is permanent solutions.

  • crossRT Oct 30, 2014 @ 16:17

    1G RAM VPS get this error
    dd: memory exhausted by input buffer of size 1073741824 bytes (1.0 GiB)
    anyone can help?

  • Andrew Wippler Nov 23, 2014 @ 21:00

    dd if=/dev/zero of=/swapfile bs=1G count=4 creates a 4GB file – not 2GB like the tutorial states

  • fsa Nov 27, 2014 @ 22:32

    @crossRT simply reduce the buffer size, like:
    sudo dd if=/dev/zero of=/swapfile bs=500M count=4
    Results in ->
    -rw-r–r– 1 root root 2.0G Nov 27 23:31 /swapfile

    • crossRT Dec 2, 2014 @ 15:42

      yeah, i did it with fallocate command.
      Anyway, thanks! =)

  • Rishitha Minol Nov 29, 2014 @ 18:18

    This is useful.
    # dd if=/dev/zero of=/swapfile bs=1G count=4 did not worked.
    but “# dd if=/dev/zero of=swapfile bs=M count=2000” worked instead of that.

  • winar Mar 31, 2015 @ 8:03

    more easy with this command :
    root@sites:~# dd if=/dev/zero of=/swapfile bs=1M count=1024
    root@sites:~# mkswap /swapfile
    root@sites:~# nano /etc/fstab
    than add this line :
    /swapfile swap swap defaults 0 0

  • saidesh Jan 9, 2017 @ 13:03

    i added swap file but now showing in free command. is there any issue

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum