Step-by-Step Guide: How to Increase Swap Space in Ubuntu
Traducciones al EspañolEstamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.
Systems trying to run large, memory-intensive applications with limited RAM can run into serious issues. Operations might become very slow, and the application can sometimes freeze completely or crash with out-of-memory errors. One workaround for this issue is to create extra swap space on the hard drive. The application can use this extra memory supply when RAM is running low. This guide explains the concept of swap space, and demonstrates how to increase swap space on Ubuntu.
To understand how swap space works, it is also important to distinguish between two types of computer memory. These are Random Access Memory (RAM) and the more permanent hard disk drive (HDD) or solid-state drive (SSD) storage. RAM memory is volatile and designed to temporarily hold data during program execution. The RAM contents change quickly and require electricity to maintain. If power to the system is shut down, all data in RAM is lost. The storage drives are designed to permanently store data. If the system is rebooted, the data on the drive is still intact. Computer storage drives have a much larger capacity than RAM does, but RAM access is significantly faster.
Swap space is located on the system’s storage drive. A swap file is a pre-allocated file that is configured to hold system swap data. A swap file is easier to resize than a partition when more swap space is required. On a virtual machine, where partitions are not available, a swap file is the only available option.
Even though the swap file is located on the storage drive, the system can use this space as if it were part of RAM. Active program data can be temporarily stored in either place. This process is not transparent to the user, as it is not possible to tell where any given piece of data is being stored.
The system uses RAM preferentially, but switches to using the swap space as necessary. As working memory is used up, Ubuntu temporarily stores data or modules in the swap area. Many programs are optimized to keep frequently used information in RAM, while background or inactive data is stored in the swap file. Ubuntu provides the user-configurable
swappiness variable to indicate how frequently swap space should be used.
As of release 17.04, Ubuntu uses a swap file rather than a partition. However, assuming your Linode is setup with our normal configurations, it has a 512MB swap disk rather than a swap file.
Swap files provide several benefits, but they have a few drawbacks too. Here are some of the advantages of using swap space.
- It helps guard against out-of-memory errors, along with related program freezes and system crashes.
- It increases the amount of functional memory and makes it easier to run memory-intensive applications.
- It enables the use of the Ubuntu hibernation feature. For more information on this feature, consult the Ubuntu swap FAQ.
Here are the main disadvantages of configuring a swap file on Ubuntu.
- It can cause excessive disk wear on older SSD drives. This is because working memory is accessed far more frequently than the permanent storage drive. Newer SSD drives do not typically have this problem.
- Accessing swap space is slower than using RAM. The penalty depends on the system architecture. However, programs with strict performance requirements can suffer significant slowdowns.
Overall, it is usually better to treat swap space as a safety mechanism to avoid memory errors and crashes. If a system has to consistently access the swap file during regular operations, consider upgrading it with more RAM.
Follow our Setting Up and Securing a Compute Instance guide to update your system. You may also wish to set the timezone, configure your hostname, create a limited user account, and harden SSH access.
sudo. If you are not familiar with the
sudocommand, see the Users and Groups guide.
The examples that follow are from Ubuntu 22.04 LTS. However, the same steps can be used for Ubuntu 20.04 LTS and 18.04 LTS. On 16.04 LTS, it is necessary to use a swap partition to add swap space. These instructions are only valid for creating a swap file on Ubuntu and are not necessarily accurate on other Linux distributions.
It is important to configure a large enough swap file. However, very large files are typically not necessary. A system with 2GB of RAM or less should have a swap file that is twice as large as the RAM. For larger systems, 4GB should suffice. The optimal amount of swap space depends on the system and how it is used.
It is possible to create multiple swap files. However, it is better to configure one swap file, especially because it is possible to resize it later. You can also use a swap file along with a swap partition.
Some systems automatically configure a swap file during installation. To determine whether the system already has a swap file, use the
swapon --showcommand. If any files are displayed, this means one or more swap files already exist. Proceed to the “How to Increase Existing Swap Space” section for information on how to resize a swap file.
sudo swapon --show
If a swap file has already been created, it is shown as follows. If there is no swap file, there is no output.
NAME TYPE SIZE USED PRIO /swapfile file 1024M 0B -2
If you created a Linode using the standard configuration, you should see a swap partition instead:
NAME TYPE SIZE USED PRIO /dev/sdb partition 512M 0B -2
Confirm swap space has not already been allocated using the
freecommand. This command can be used on most Linux systems to verify the swap space size.
If the total memory for
0B, a swap file or partition has not been created yet.
total used free shared buff/cache available Mem: 3.8Gi 523Mi 2.7Gi 3.0Mi 643Mi 3.1Gi Swap: 0B 0B 0B
If you created a Linode using the standard configuration, you should see a approximately 512MB dedicated to swap:
total used free shared buff/cache available Mem: 1.9Gi 154Mi 1.4Gi 0.0Ki 410Mi 1.6Gi Swap: 511Mi 0B 511Mi
Ensure there is enough space on the hard drive to create the swap space. Use the
df -hcommand and locate the entry for the root directory, which is listed as
/. The proposed swap file should fit comfortably within the available disk space with some room to spare. The following example indicates the hard drive has 64G of available space. This is more than adequate.
Filesystem Size Used Avail Use% Mounted on ... /dev/sda 49G 3.4G 43G 8% / ...
Allocate memory for the swap file using the
fallocatecommand. This command is used to reserve a certain amount of disc space for a file in advance. The following command creates a 1G file named
swapfilein the root directory. Always give a swap file a very obvious name to avoid confusion.
sudo fallocate -l 1G /swapfile
Change the file permissions for
rootcan write to it. This prevents other users from accidentally deleting or overwriting the file.
sudo chmod 600 /swapfile
lscommand to confirm the swap file has been successfully created. Use the
-loption to see the size of the file.
ls -hl /swapfile
-rw------- 1 root root 1.0G Nov 28 13:22 /swapfile
mkswapcommand to designate the new file as a swap file. This means it can be used for volatile memory when RAM space runs low.
sudo mkswap /swapfile
Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes) no label, UUID=97644d2b-0608-4a32-bfb1-b069af64d86b
The file swap has now been created, but it is still disabled. Activate it using the
sudo swapon /swapfile
swaponcommand can be used with the
--showoption to confirm the swap space is enabled. If the new swap file is not listed, verify the results of the previous instructions.
sudo swapon --show
NAME TYPE SIZE USED PRIO /dev/sdb partition 512M 0B -2 /swapfile file 1024M 0B -3
To confirm the amount of swap space available on Ubuntu, use the
totalcolumn for the
Swapentry should display
1.5Giof total memory (1.0GB swap file and 0.5GB swap partition).
total used free shared buff/cache available Mem: 1.9Gi 148Mi 1.4Gi 0.0Ki 416Mi 1.6Gi Swap: 1.5Gi 0B 1.5Gi
At this point, the new swap file is fully functional and the system can use it. Unfortunately, the file is not permanent. The swap file disappears after a system reboot and must be recreated before it can be used again.
To automatically create the swap file when the system boots, add it to the
/etc/fstab file. Each entry in this file contains the following fields, in the following order.
- Device Name: This is the full path and name of the swap file. In this example, it is
- Default Mount Point: This must be
- Filesystem Type: This is also
- The Mount Options: Use the keyword
defaultsto use the system defaults.
- Dump Options: Set this to
- Filesystem Check Options: This must also be set to
To add an entry to the
fstab file, follow these steps:
As a precaution, make a backup copy of the existing
sudo cp /etc/fstab /etc/fstab.bak
Edit the file using a text editor.
sudo nano /etc/fstab
Add the following line to the end of the file.
- File: /etc/fstab
/swapfile swap swap defaults 0 0
Save and close the file. The swap file should appear automatically after a system reboot.
The swappiness property controls how aggressively Ubuntu swaps data out of RAM. This setting extends from 0 to 100. Higher values tell the system to use the swap file more often. Configure a setting at the upper end of this range to ensure RAM is also available for other applications. Unfortunately, a very high setting can compromise performance. A low swappiness setting means the system is less likely to use the swap mechanism. Use a setting closer to zero when application performance is important.
To adjust the
swappiness setting, use the following procedure.
Verify the current
swappinesssetting. The default value is
To temporarily adjust the value of
swappiness, use the
sysctlutility. The following command lowers the value to
sudo sysctl vm.swappiness=50
vm.swappiness = 50
To permanently change this value, edit the
sysctl.conffile. Add the following line to the bottom of the file.
- File: /etc/sysctl.conf
One advantage of using a swap file over the old partitioning method is the relative ease to resize an existing swap. On an Ubuntu system, follow these steps to add swap space.
Disable the swap mechanism. Active applications cannot use the swap file while it is disabled.
sudo swapoff -aThis also temporarily disables your swap partition until the next reboot.
Resize the swap space.
fallocatecan only be used to generate a new file, so the
ddcommand must be used instead. Set the individual parameters as follows:
ifmust be set to
ofvariable, standing for “output file”, must be set to the name of the swap file. In this example it is set to
bs, or “block size”, to
The value for
countindicates how many blocks are allocated. To determine the value of
count, divide the intended file size by the block size. For example, set the value of
2to generate a 2G swap file.
sudo dd if=/dev/zero of=/swapfile bs=1G count=2
2+0 records in 2+0 records out 2147483648 bytes (2.1 GB, 2.0 GiB) copied, 7.86524 s, 273 MB/s
Ensure the permissions are set correctly.
sudo chmod 600 /swapfile
Convert the file back into swap format.
sudo mkswap /swapfile
Setting up swapspace version 1, size = 2 GiB (2147479552 bytes) no label, UUID=6e61561d-c03d-4911-9343-8aa4c234576a
Enable the swap file.
sudo swapon /swapfileTo also re-enable the swap partition, use
sudo swapon -ainstead.
Confirm the file has been resized correctly and is ready for use using either the
total used free shared buff/cache available Mem: 1.9Gi 138Mi 1.0Gi 0.0Ki 771Mi 1.6Gi Swap: 2.0Gi 0B 2.0Gi
sudo swapon --show
NAME TYPE SIZE USED PRIO /swapfile file 2G 0B -2
cat /etc/fstabor edit the swappiness value again, because those items are unaffected by the change.
A swap file is used to avoid running out of RAM when using memory-intensive applications. Ubuntu uses swap space to store information that would ordinarily be held in RAM on the hard drive. This guards against freezes and crashes, but can negatively affect performance.
Most systems are designed to hold active memory in RAM under normal circumstances. However, the
swappiness setting configures the system to use the swap space more or less preferentially. This guide provides detailed instructions on how to increase swap space on Ubuntu. The memory for a swap file can be allocated using the Ubuntu
fallocate command. The file can then be converted into swap space using the
mkswap command, and enabled with
You can configure swap space on a Linode whenever you are temporarily running a memory-intensive application, or as a preventative measure. Choose from a high-performance Dedicated CPU service, or a flexible and affordable Shared CPU alternative.
You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.
This page was originally published on