How to create a Linux swap file

I am a new Linux system developer and user. How do I create a Linux swap file from the command line option for my cloud server? How can I add swap space on my Ubuntu 20.04 LTS or CentOS Linux 7/8 server?

Swap space is nothing but disk, partition, or file control by the Linux kernel memory subsystem. The Linux kernel uses swap space when the server starts to run out of physical RAM (Random-access memory). In other words, swap space will hold inactive pages. A combination of physical RAM and swap is described as virtual memory. Swap space is also critical for Linux laptop and desktop users for hibernation purposes. Linux desktop users use the swap space to save the RAM contents before hibernation.
Tutorial requirements
Operating system/appLinux
Root privileges requiredYes
DifficultyEasy (rss)
Estimated completion time5m
Table of contents

ADVERTISEMENTS

Steps for creating a Linux swap file

  1. Display current swap space and RAM usage on Linux:
    $ free -h
    $ swapon --summary
  2. Next, create a new file that you will use for swap space either using the dd command:
    # Example: 2 Gib Linux swap file #
    $ sudo dd if=/dev/zero of=/swap-file count=2 bs=1GiB
  3. Make sure you set up correct Linux filesystem permissions for security reasons using the chmod command and chown command:
    $ sudo chmod -v 0600 /swap-file
    $ sudo chown -v root:root /swap-file
    # List permissions #
    $ ls -l /swap-file
  4. Run the following mkswap command to set up Linux swap area using a file:
    $ sudo mkswap /swap-file
  5. Activating a swap space by typing the swapon command:
    $ sudo swapon /swap-file
How to create a Linux swap file

Adding swap file on Linux using the CLI

Displaying RAM and swap usage on Linux

You can use any one of the following commands:
$ swapon --summary
$ free -h
$ top
$ htop
$ vmstat

How to add swap file and display it on Linux commands

Display swap usage summary on Linux

See my tutorial “How To Check Swap Usage Size and Utilization in Linux” for a detailed explanation about swap usage.

How to activate swap space file persistently on Linux

Make sure our swap file is activated after the Linux system reboots. To make the change permanent, edit the /etc/fstab file:
$ sudo vi /etc/fstab
Append the following config directives:
/swap-file swap swap defaults 0 0
Save and close the file.

How to set up the swap space and file priority

By default, the Linux kernel uses the first activated swap space till it is full. Then kernel starts using the second swap space and so on. Nevertheless, Linux allows us to define priority. The default priority is -2, and Linux can use the highest priority first. Edit /etc/fstab and add the pri as follows:

/dev/sdb none swap sw  0 0
/swap-file swap swap pri=5 0 0
/swap-file-2 swap swap pri=10 0 0

Now my Linux kernel uses /swap-file-2 first with pri=10. When that space is full, Linux usess the /swap-file with pri=5. Finally, Linux uses /dev/sdb which has -2 priority.

A note about the swappiness

The swappiness value is defined in /proc/sys/vm/swappiness file. It controls how aggressively the Linux kernel will swap memory pages. Higher values increase aggressiveness, and lower values decrease aggressiveness. The default value is 60. Use the cat command to see values:
$ cat /proc/sys/vm/swappiness
60

I recommend leaving the default value, which works out great for most users. However, you can change it as follows to say 40:
$ sudo echo "vm.swappiness=10" | sudo tee -a /etc/sysctl.d/99-swappiness.conf
See “How to append text to a file when using sudo command on Linux or Unix” and “How to make changes to /proc/ filesystem permanently using sysctl.conf” for more information.

Removing swap file

Want to delete your swap file? Try:

  1. Disable the swap file:
    $ sudo swapoff -v /swap-file
  2. Remove the physical swap file using the rm command:
    $ sudo rm -v -i /swap-file
  3. Edit the /etc/fstab and remove entry for the swap file. For example:
    /swap-file swap swap defaults 0 0

Conclusion

You learned about creating a swap file on Linux to optimize VM/bare metal server or Linux desktop to increase available swap space. See the following man pages/documenation for more information by typing the man command:
$ man 8 mkswap
$ man 8 swapon
$ man 8 swapoff
$ man 8 mount
$ man 5 fstab

🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig 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 VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
4 comments… add one
  • Anonymous Sep 10, 2020 @ 11:08

    Hi,

    Swappiness can be set to values between 0 and 100 only. I leared this other day. A low value means the kernel will try to avoid swapping as much as possible. Good for database server as I do not want swapping. A higher value instead will make the kernel aggressively try to use swap space. Like we have tons of VM and I set swappiness to 100. Why? Because we have PCI SSD running in RAID-10. Not fast as RAM but it helps other VMs ;)

  • DrsOps Sep 10, 2020 @ 11:28

    Hi Vivek,

    Would you mind removing fallocate(1) this post? From the swapon(8):

    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 files with holes or on copy-on-write files on filesystems like Btrfs.

    Commands like cp(1) or truncate(1) create files with holes. These files will be rejected by swapon.

    Preallocated files created by fallocate(1) may be interpreted as files with holes too depending of the filesystem. Preallocated swap files are supported on XFS since Linux
    4.18.

    The most portable solution to create a swap file is to use dd(1) and /dev/zero.

    Otherwise good intro.

  • Thiago Ferreira Sep 14, 2020 @ 10:49

    Remember to change also the grub after any modification, because there is a line that call the swap path there in grub.cfg.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.