Home > Linux, Tyler B > Using a swap file instead of a swap partition in linux

Using a swap file instead of a swap partition in linux

Historically linux distributions have created a dedicated partition to be used as swap space and while this does come with some advantages there are other issues with it as well. Being a fixed size partition means it is relatively difficult to later change your mind about how much swap your system actually needs.

Thankfully there is another way: using a swap file instead of a swap partition.

To do this all you need to do is create a file that will hold your swap, set the right permissions to it, format it and use it. The ArchWiki has an excellent guide on the whole process here but I’ve re-created my steps below.

I like to use fallocate but you could also use dd or whatever. For example the following will create a 2GB swap file in the root directory:

sudo fallocate -l 2G /swapfile

Next up set the permissions:

sudo chmod 600 /swapfile

Format it:

sudo mkswap /swapfile

Use it:

sudo swapon /swapfile

That’s pretty much it. At this point you have the ability to add as much swap (via swap files) as you’d like. If you ever want to stop using swap, for example to get rid of the file when you’re done, simply issue the following command:

sudo swapoff /swapfile

One other thing to note is that every time you reboot your system you will have to re-run the swapon command above. To avoid this you can add it to your fstab file so that it is done on startup.

/swapfile none swap defaults 0 0

The nice thing about using swap files is that they are really flexible, allowing you to allocate as much or as little as you need at any given time.

Categories: Linux, Tyler B Tags: ,
  1. anon
    April 15th, 2017 at 08:45 | #1

    How do you make /swapfile dynamic?

    i tried sudo apt-get install swapspace but i couldn’t get it to reduce /swapfile size to 0 bytes.

  2. Tyler B
    May 7th, 2017 at 09:09 | #2

    anon :

    How do you make /swapfile dynamic?

    i tried sudo apt-get install swapspace but i couldn’t get it to reduce /swapfile size to 0 bytes.

    So I don’t actually have any experience with Swapspace but my understanding is the same as yours – that it grows and shrinks as needed. Although that said it’s not clear to me if the file ever actually shrinks, or if files just go away when they aren’t needed. This may be why you are never seeing a size of 0 bytes (if it was going to be 0 it would have been disabled and gone away anyway).

  1. No trackbacks yet.