How to create a swap file on linux

In this article, we will explain swap space, and learn how to create swap space using a swap file in Linux: this is important in case we don’t have a swap partition created on the hard disk.

Swap space/partition is space on a disk created for use by the operating system when memory has been fully utilized. It can be used as virtual memory for the system; it can either be a partition or a file on a disk.

When the kernel runs out of memory, it can move idle/inactive processes into swap creating room for active processes in the working memory. This is memory management that involves swapping sections of memory to and from virtual memory.

With that said, below are the steps we can follow to create a swap space using a file.

How to Create and Enable Swap in Linux

1. In this example, we will create a swap file of size 2GB using the dd command as follows. Note that bs=1024 means read and write up to 1024 bytes at a time and count = (1024 x 2048)MB size of the file.

Alternatively, use the fallocate command as follows.

And then set the appropriate permissions on the file; make it readable only by root user as follows.

2. Now setup the file for swap space with the mkwap command.

3. Next, enable the swap file and add it to the system as a swap file.

4. Afterwards, enable the swap file to be mounted at boot time. Edit the /etc/fstab file and add the following line in it.

In the line above, each field means:

  • /mnt/swapfile – device/file name
  • swap – defines device mount point
  • swap – specifies the file-system type
  • defaults – describes the mount options
  • 0 – specifies the option to be used by the dump program
  • 0 – specifies the fsck command option

6. To set how often the swap file can be used by the kernel, open the /etc/sysctl.conf file and add the line below.

Note that the default value of how frequent swap space can be used is 60 (maximum value is 100). The higher the number, the more frequent swap space utilization by the kernel. When the value is set to 0, the swap file will only be used if the operating system has fully utilized memory.

6. Now verify the swap file was created using the swapon command.

Check Swap Space in Linux

We can optionally reboot the system to effect the above changes using the following command.

Remember to also read through these useful Linux memory management guides:

That’s It! If you have any issues, use the feedback form below to send us any questions or important additional ideas to this topic.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Last updated on: 2018-11-29

Authored by: Trey Hoehne

Swap is space on a disk that is reserved for use as virtual memory. When a Linux® server runs out of memory, the kernel can move inactive processes into swap space to make room for active processes in the working memory.

By default, a swap partition is not present on Cloud Servers, but you can add swap to a server by allocating a swap file. The performance of a swap file is similar to that of a swap partition. However, using a swap file makes it easier to control the swap size without repartitioning a volume. You can control how aggressively the server uses this swap space by modifying the system’s swappiness value.

The steps below show how to create a swap file on Linux and modify a system’s swappiness value.

How do I add a swap file?

The following steps show how to add 1GB of swap to your server:

Create the file that you want to use for swap by entering the following command:

If the fallocate command fails or isn’t installed, run the following command:

Format the swap file by entering the following command:

Add the file to the system as a swap file by entering the following command:

Add the following line to the end of /etc/fstab to make the change permanent:

To change the swappiness value, add the following line to the file at /etc/sysctl.conf :

Start with a value of 10 and increase if it necessary. A typical default value for swappiness is 60. The higher the number (up to 100), the more often the system uses swap.

The degree to which swappiness affects performance depends on how your memory is currently used. We recommend that you experiment to find an optimal value. At 0, the system only uses the swap file when it runs entirely out of memory. Higher values enable the system to swap idle processes out in order to free memory for disk caching, potentially improving overall system performance.

Check that the swap file was created by entering the following command:

Reboot the server to ensure that the changes take effect.

Note: Following these instructions on a new Rackspace server makes the resulting swap file world-readable. To prevent the file from being world-readable, you should set up the correct permissions on the swap file by running the following command:

In most cases, the only user that needs access to the swap partition is the root user.

Share this information:

©2020 Rackspace US, Inc.

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License

Last updated August 29, 2019 By Abhishek Prakash 53 Comments

This tutorial discusses the concept of swap file in Linux, why it is used and its advantages over the traditional swap partition. You’ll learn how to create swap file or resize it.

What is a swap file in Linux?

A swap file allows Linux to simulate the disk space as RAM. When your system starts running out of RAM, it uses the swap space to and swaps some content of the RAM on to the disk space. This frees up the RAM to serve more important processes. When the RAM is free again, it swaps back the data from the disk. I recommend reading this article to learn more about swap on Linux.

Traditionally, swap space is used as a separate partition on the disk. When you install Linux, you create a separate partition just for swap. But this trend has changed in the recent years.

With swap file, you don’t need a separate partition anymore. You create a file under root and tell your system to use it as the swap space.

With dedicated swap partition, resizing the swap space is a nightmare and an impossible task in many cases. But with swap files, you can resize them as you like.

Recent versions of Ubuntu and some other Linux distributions have started using the swap file by default. Even if you don’t create a swap partition, Ubuntu creates a swap file of around 1 GB on its own.

Let’s see some more on swap files.

How to create a swap file on linux

Check swap space in Linux

Before you go and start adding swap space, it would be a good idea to check whether you have swap space already available in your system.

You can check it with the free command in Linux. In my case, my Dell XPS has 14GB of swap.

The free command gives you the size of the swap space but it doesn’t tell you if it’s a real swap partition or a swap file. The swapon command is better in this regard.

As you can see, I have 14.9 GB of swap space and it’s on a separate partition. If it was a swap file, the type would have been file instead of partition.

If you don’ have a swap space on your system, it should show something like this:

The swapon command won’t show any output.

Create swap file on Linux

If your system doesn’t have swap space or if you think the swap space is not adequate enough, you can create swap file on Linux. You can create multiple swap files as well.

Let’s see how to create swap file on Linux. I am using Ubuntu 18.04 in this tutorial but it should work on other Linux distributions as well.

Step 1: Make a new swap file

First thing first, create a file with the size of swap space you want. Let’s say that I want to add 1 GB of swap space to my system. Use the fallocate command to create a file of size 1 GB.

It is recommended to allow only root to read and write to the swap file. You’ll even see warning like “insecure permissions 0644, 0600 suggested” when you try to use this file for swap area.

Do note that the name of the swap file could be anything. If you need multiple swap spaces, you can give it any appropriate name like swap_file_1, swap_file_2 etc. It’s just a file with a predefined size.

Step 2: Mark the new file as swap space

Your need to tell the Linux system that this file will be used as swap space. You can do that with mkswap tool.

You should see an output like this:

Step 3: Enable the swap file

Now your system knows that the file swapfile can be used as swap space. But it is not done yet. You need to enable the swap file so that your system can start using this file as swap.

Now if you check the swap space, you should see that your Linux system recognizes and uses it as the swap area:

Step 4: Make the changes permanent

Whatever you have done so far is temporary. Reboot your system and all the changes will disappear.

You can make the changes permanent by adding the newly created swap file to /etc/fstab file.

It’s always a good idea to make a backup before you make any changes to the /etc/fstab file.

Now you can add the following line to the end of /etc/fstab file:

You can do it manually using a command line text editor or you just use the following command:

Now you have everything in place. Your swap file will be used even after you reboot your Linux system.

Adjust swappiness

The swappiness parameters determines how often the swap space should be used. The swappiness value ranges from 0 to 100. Higher value means the swap space will be used more frequently.

The default swappiness in Ubuntu desktop is 60 while in server it is 1. You can check the swappiness with the following command:

Why servers should use a low swappiness? Because swap is slower than RAM and for a better performance, the RAM should be utilized as much as possible. On servers, the performance factor is crucial and hence the swappinness is as low as possible.

You can change the swappiness on the fly using the following systemd command:

This change it only temporary though. If you want to make it permanent, you can edit the /etc/sysctl.conf file and add the swappiness value in the end of the file:

Resizing swap space on Linux

There are a couple of ways you can resize the swap space on Linux. But before you see that, you should learn a few things around it.

When you ask your system to stop using a swap file for swap area, it transfers all the data (pages to be precise) back to RAM. So you should have enough free RAM before you swap off.

This is why a good practice is to create and enable another temporary swap file. This way, when you swap off the original swap area, your system will use the temporary swap file. Now you can resize the original swap space. You can manually remove the temporary swap file or leave it as it is and it will be automatically deleted on the next boot.

If you have enough free RAM or if you created a temporary swap space, swapoff your original file.

Now you can use fallocate command to change the size of the file. Let’s say, you change it to 2 GB in size:

Now mark the file as swap space again:

And turn the swap on again:

You may also choose to have multiple swap files at the same time.

Removing swap file in Linux

You may have your reasons for not using swap file on Linux. If you want to remove it, the process is similar to what you just saw in resizing the swap.

First, make sure that you have enough free RAM. Now swap off the file:

The next step is to remove the respective entry from the /etc/fstab file.

And in the end, you can remove the file to free up the space:

Do you swap?

I think you now have a good understanding of swap file concept in Linux. You can now easily create swap file or resize them as per your need.

If you have anything to add on this topic or if you have any doubts, please leave a comment below.

Like what you read? Please share it with others.

Affiliate disclosure: In full transparency – some of the links on this website are affiliate links (Udemy), if you use them to make a purchase we will earn a commission at no additional cost for you (none whatsoever!). Will this be a problem? This is how we manage to create free content for you.

In this tutorial, we will demonstrate a step by step guide to create swap file on Linux with examples. The process is same for Ubuntu and any other Linux distribution.

How to create a swap file on linux

What is Swap File?

Swap is a space on the disk that is used when the amount of your physical RAM memory is full. The inactive pages will be moved to swap space from RAM when the system runs out of memory.

In most of the cases, a swap partition or swap space won’t be present and you will end with out of memory issue. In such cases the only option is to create a swap file.

This tutorial was tested on Linux bases systems with Ubuntu 20.04 and CentOS 8 but it should work with any other Linux distribution.

Create Swap File on Linux

Follow below steps to add 1G of swap to your server. If you want to add more swap then replace the 1G with 2G , or 4G .

Note: Anything over 4G of swap is probably unnecessary if you are just using it as a RAM fallback.

Step 1: Create a file that we will be used for swap space.

Step 2: Set the permissions to the swap file so that only root user can write or read the file.

Step 3: Use mkspace to set up the file as Linux swap area.

Step 4: Run the below command to enable the swap.

This is temporary. To make changes permanent, open the /etc/fstab file and copy and paste the below snippet in newline.

Step 5: To verify that the swap is active, you can use either swapon or free command as shown below,

Tweak Swap Settings

The swappiness property defines how often the system will use the swap space. This is a value between 0 and 100.

The lower value tells Linux kernel to avoid swapping whenever possible, while the higher values tells use swap space more aggressively.

You can check the current swappiness value by executing below command,

The default swappiness value is set to 60.

The default swappiness value is OK for most of the Linux systems, but would recommend to set lower value for production servers.

To modify the swappiness value, run the below command,

This will set value to 10 and to make this value persistent during reboot add the below code snippet to the /etc/sysctl.conf file.

How to Remove Space File

Follow below steps to remove the swap file for any reason.

Step 1: First deactivate the swap.

Step 2: Remove the swap file entry /swapfile swap swap defaults 0 0 from the /etc/fstab file.

Step3 : Now delete the actual swapfile file using the rm command:

Conclusion

We hope this tutorial helped you to create swap file on Linux and also how to deactivate or delete the swap file.

If you face any issues, please do let us know in the comment section. We are happy to help you.

Please do share it with your friends and don’t forget to follow us on Facebook, Twitter and LinkedIn. Visit our Sysadmin Hub for more tutorials and updates.

How to create a swap file on linux

A swap file can be created while installing Linux operating system, if you forgot to do so you can read this tutorial and create one after installation. Even if you need additional swap memory this tutorial will be useful. I’ve only explained the command line way of creating a swap file which most administrators will use, its upto you to explore the GUI technique. For executing the commands in this tutorial you need to have root access or atleast sudo permissions for these commands and permissions to edit the fstab file.

Step 1: Create a dummy file for the required size

If you are using a hard disk partition skip this step. The first step is to create a dummy file of the required file size. The dd command will be used, a dummy file of the specified size will be created. Use the following command

dd if=/dev/zero of=/swapfile1 bs=1M count=1024

The above command will create a 1 GB file /swapfile1. The bs is the number of bytes and count is the number of times to create such bytes so 1M*1024=1GB. You can specify any location for the swap e.g. /root/swpfile, /swaps/swapfile1 Just ensure the directory exists before executing the above command

Step 2: Format it with filesystem swap

The dummy file must be formatted to filesystem type swap, use mkswap to do this execute any one of the following command

mkswap /swapfile1
mkswap -L myswap1 /swapfile1

The second command labels the file with the name myswap1. If you are formatting a device specify the device name

mkswap /dev/sda4
mkswap -L swap1 /dev/sda4

Step 3: Add an entry to the /etc/fstab file

Adding an entry to the /etc/fstab file ensures the file is mounted as swap everytime the system boots. Open /etc/fstab with a text editor and add any one of the following lines

/swapfile1 swap swap defaults 0 0
/dev/sda4 swap swap defaults 0 0

save the file and exit.

Step 4: Check if the configuration is right and mount the swap file.

Use the swapon command to do this

If you see any errors check the /etc/fstab file and correct it. Make sure you reboot the system only AFTER all errors are rectified.

How to create a swap file on linux

In Linux, a swap is an assigned area in the hard disk to hold temporary data. It works the same way as memory RAM, except that it is located within the hard disk instead of the RAM. Think of it as a backup to your RAM. When the RAM is full, temporary data in the RAM are moved to the swap to free up space in the RAM.

In computers with 4GB or less of RAM, it is often advised to have a dedicated swap partition that is of the same size as the RAM in the system. So for a 4GB computer, it is good to a swap partition of 4GB.

However, the computers nowadays come with more RAM than required, and swapping does not occur as frequent. As such, it is a waste to setup a dedicated swap partition that is not doing anything. A swap file is a better choice in this case.

What is a Swap File?

Same as the swap partition, a swap file is a swap that exists in the form of a file, rather than a partition. The good thing about a swap file is that it can be added/removed easily and there is no need to worry about the partition size as it can be expanded/shrunk as you wish.

How to Create a Swap File

It is easy to create a swap file in Linux.

1. Open a terminal. To create a swap file of 2GB, type the following:

Alternatively, if the above command fails, use this command instead:

2. Next, format the swap file:

3. Change the permission:

4. Activate the swap file:

That’s it. To check if the swap file is working:

How to create a swap file on linux

To mount the swap file on boot up, first open up the “/etc/fstab” file:

And add this line to the end of the file:

Save and exit the file.

Swappiness

The swappiness value of a swap file determines how often the swap file is used to store temporary data. The swappiness value is a number from 0 to 100. The default value is 60. You can check it with the command:

The higher the value, the more likely the swap file will be used. In ideal case, you won’t want the swappiness value to be too high.

To change the swappiness value, open the file “/etc/sysctl.conf”

and add the swappiness value in it:

Save and exit the file.

Removing the swap file

If you need to remove the swap file, do it in the reverse order:

1. Remove the swap entry from the “/etc/fstab” file.

2. Deactivate swap:

3. Remove the swap file

Wrapping Up

Unless you are still using a old computer with less than 4GB of RAM, it is better to use a swap file than a dedicated swap partition, as it is easier to create and manage.

SWAP is a space in hard disk that allocated as virtual memory to help physical memory ( RAM ). Your kernel removes the least used memory pages in RAM to the SWAP space when the RAM space is full. SWAP also as memory storage when we hibernate the computer.

There are two types of SWAP, SWAP partition, and SWAP file. When we install the operating system, installers typically create a SWAP partition. Alternatively, we can use the SWAP file method when there is no left unallocated disk.

How to create a SWAP File

First off, make sure there is spare space available in your disk. SWAP require at least the size of your physical memory. For instance, your minimum SWAP size is 8GB if your RAM is 8GB. To check available space in your disk, run df -h

So we have 24GB free of space, lets create a 8GB SWAP file.

If you are using XFS file system, probably fallocate will result an error like swapon failed: Invalid argument. Alternatively, we can use dd command altrough it takes more time to process.

Then we will get a message like this:
$sudo dd if=/dev/zero of=/swapfile count=8000 bs=1MiB
8000+0 records in
8000+0 records out
8388608000 bytes (8.4 GB, 7.8 GiB) copied, 130.398 s, 64.3 MB/s

After allocating 8GB of space in /swapfile, lets change the permission to 600

Then let’s convert /swapfile into swap by executing mkswap command

DONE! We have created a SWAP file. Let’s activate it. Run swapon

To verify if our SWAP file is activated, run $sudo swapon -s

Now we have an active SWAP in our laptop, that’s great! However, when we restart our laptop , the SWAP space will be not active and we need to activate it manually. To fix this issue, we need to add a rule in /etc/fstab file for /swapfile.

To add rule in /etc/fstab, open /etc/fstab with your favorite text editor, then append this line

Alternatively, you can accomplish it by running this command

How to create a SWAP partition

On article above, we had created SWAP space in file mode, but for this time we will create a SWAP space in partition mode. Make sure you have spare unallocated space in your disk.

For this case, I will use my secondary hard disk (/dev/sdb) and check unallocated space with parted program.

So we have 100% free space, then we can allocate 8GB for SWAP partition. Let’s create SWAP partition using parted program and follow the dialog/wizard.

To check our new SWAP partition, run print

Quit parted by typing quit then let’s convert that partition to a SWAP format.

Done! We had created a SWAP partition, to activate it, run sudo swapon /dev/sdb1 and to check the result run sudo swapon -s . And again, that SWAP partition will not activated after reboot. We need to add new rule in /etc/fstab

The Simplest Way to Add SWAP Partition in Linux (GUI)

Now it’s time get the simplest way to add SWAP partition in Linux. This method is preferrable if you are using desktop environment, because we will create SWAP partition in KDE Partition Manager. KDE Partition Manager is a GUI application for KDE desktop environment. If you are using GNOME then GParted is preferrable. No worries, these softwares are work similar.

How to create a swap file on linux KDE Partition Manager

  • First step is open your KDE Partition Manager, then select the hard disk.
  • Right click unallocated row, then click new
  • Set the parameters like on screenshot below then click OK

How to create a swap file on linux

  • It will show you a new partition in the partition list. In order to write our changes to disk, clik edit >apply. Click confirm operation.
  • To activate SWAP partition, right click the partition and click activateSWAP
  • However, we still need to manually add /etc/fstab rule to activate SWAP partition every booting.

How to create a swap file on linuxThe swap space is an area of the hard disk that is used when the RAM runs out of memory. If your system has enough RAM it is generally not necessary to have swap space. However, if you have installed Linux without creating any swap partition and later want some swap space, you can easily do so. You can either create a swap partition or create a swap file.

The swap file approach is simpler and safer if you want to add swap space post OS installation. Beside, swap file and swap partition have the same performance now. I carried out the instructions I am giving here on Ubuntu 10.10, but it should work on any other distributions as well.

The first thing we need to do is create an empty file of the required size. To do this open the Terminal and execute the command given below. In this example I am creating a 3GB swap file. You will not probably need that much. So, enter your own value.

$ cd /

$ sudo dd if=/dev/zero of=swapfile bs=1M count=3000

To set it as 1GB, change the count value (3000 in the example above) to 1000, 1500 for 1.5GB etc.

Now change the file created to a swap file with the command below.

$ sudo mkswap swapfile

Turn on the swap file with the command,

$ sudo swapon swapfile

To ensure that the swap file is turned on automatically at system startup, open fstab.

$ sudo nano etc/fstab

And add the line given below. Save and close.

/swapfile none swap sw 0 0

That is it. You can check if the system is using the swap file you created with the command

SWAP is a space in hard disk that allocated as virtual memory to help physical memory ( RAM ). Your kernel removes the least used memory pages in RAM to the SWAP space when the RAM space is full. SWAP also as memory storage when we hibernate the computer.

There are two types of SWAP, SWAP partition, and SWAP file. When we install the operating system, installers typically create a SWAP partition. Alternatively, we can use the SWAP file method when there is no left unallocated disk.

How to create a SWAP File

First off, make sure there is spare space available in your disk. SWAP require at least the size of your physical memory. For instance, your minimum SWAP size is 8GB if your RAM is 8GB. To check available space in your disk, run df -h

So we have 24GB free of space, lets create a 8GB SWAP file.

If you are using XFS file system, probably fallocate will result an error like swapon failed: Invalid argument. Alternatively, we can use dd command altrough it takes more time to process.

Then we will get a message like this:
$sudo dd if=/dev/zero of=/swapfile count=8000 bs=1MiB
8000+0 records in
8000+0 records out
8388608000 bytes (8.4 GB, 7.8 GiB) copied, 130.398 s, 64.3 MB/s

After allocating 8GB of space in /swapfile, lets change the permission to 600

Then let’s convert /swapfile into swap by executing mkswap command

DONE! We have created a SWAP file. Let’s activate it. Run swapon

To verify if our SWAP file is activated, run $sudo swapon -s

Now we have an active SWAP in our laptop, that’s great! However, when we restart our laptop , the SWAP space will be not active and we need to activate it manually. To fix this issue, we need to add a rule in /etc/fstab file for /swapfile.

To add rule in /etc/fstab, open /etc/fstab with your favorite text editor, then append this line

Alternatively, you can accomplish it by running this command

How to create a SWAP partition

On article above, we had created SWAP space in file mode, but for this time we will create a SWAP space in partition mode. Make sure you have spare unallocated space in your disk.

For this case, I will use my secondary hard disk (/dev/sdb) and check unallocated space with parted program.

So we have 100% free space, then we can allocate 8GB for SWAP partition. Let’s create SWAP partition using parted program and follow the dialog/wizard.

To check our new SWAP partition, run print

Quit parted by typing quit then let’s convert that partition to a SWAP format.

Done! We had created a SWAP partition, to activate it, run sudo swapon /dev/sdb1 and to check the result run sudo swapon -s . And again, that SWAP partition will not activated after reboot. We need to add new rule in /etc/fstab

The Simplest Way to Add SWAP Partition in Linux (GUI)

Now it’s time get the simplest way to add SWAP partition in Linux. This method is preferrable if you are using desktop environment, because we will create SWAP partition in KDE Partition Manager. KDE Partition Manager is a GUI application for KDE desktop environment. If you are using GNOME then GParted is preferrable. No worries, these softwares are work similar.

How to create a swap file on linux KDE Partition Manager

  • First step is open your KDE Partition Manager, then select the hard disk.
  • Right click unallocated row, then click new
  • Set the parameters like on screenshot below then click OK

How to create a swap file on linux

  • It will show you a new partition in the partition list. In order to write our changes to disk, clik edit >apply. Click confirm operation.
  • To activate SWAP partition, right click the partition and click activateSWAP
  • However, we still need to manually add /etc/fstab rule to activate SWAP partition every booting.