How can I create a swap file?

I know how to create and use a swap partition but can I also use a file instead?

How can I create a swap file on a Linux system?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I myself have on several machines a swap file on mdadm RAID, therefore there’s a bit of overhead. But anyway, if you adjust vm.swappiness wisely to a more acceptable value than 60, which is the default, you should have no problem.

For instance, I have 32GB RAM server with 32GB swap file on RAID6 with vm.swappiness = 1. Quoting the Wikipedia:

vm.swappiness = 1: Kernel version 3.5 and over, as well as Red Hat kernel version 2.6.32-303 and over: Minimum amount of swapping without disabling it entirely.

In this example, we create a swap file:

  • 8GB in size
  • Located in /raid1/

Change these two things accordingly to your needs.

  1. Open terminal and become root (su); if you have sudo enabled, you may also do for example sudo -i; see man sudo for all options):
    sudo -i
  2. Allocate space for the swap file:
    dd if=/dev/zero of=/raid1/swapfile bs=1G count=8

Optionally, if your system supports it, you may add status=progress to that command line.

Note, that the size specified here in G is in GiB (multiples of 1024).

  1. Change permissions of the swap file, so that only root can access it:
    chmod 600 /raid1/swapfile
  2. Make this file a swap file:
    mkswap /raid1/swapfile
  3. Enable the swap file:
    swapon /raid1/swapfile
  4. Verify, whether the swap file is in use:
    cat /proc/swaps
  5. Open a text editor you are skilled in with this file, e.g. nano if unsure:
    nano /etc/fstab
  6. To make this swap file available after reboot, add the following line:
    /raid1/swapfile        none        swap        sw        0        0

Method 2

$ sudo fallocate -l 1G /swapfile
$ sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576
$ sudo chmod 600 /swapfile
$ sudo mkswap /swapfile
$ sudo swapon /swapfile

Editor’s note: Step 1 and Step 2 are interchangeable.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x