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.



4 Comments

  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. 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).

  3. You set the file size. This can be changed very easy. The swap flows in amd out as it needs to. He set his to 2gb. Most systems set a partition to 3.88gb. So you just set it to what ypu wish. Or think you need. If you get slowing from ram heavy prosses. Then ypu can make it bigger without partition chages. Thats the point. No dynamic file size chages. I bet someone could write that command. But it would be dangerous for your regular memory. Would act like a virus more so. Also it would make partitioning the drive a safer option.

Leave a Reply

Your email address will not be published.


*