Linux: Create a swap file

Spread the love

Harddisk - Morrow Designs DISCUS 10MBRunning out of physical memory? Learn here how to create a swap file on linux.

Baseline

First check the baseline. It is possible that you have some swap already, like a swap partition (a dedicated disk partition only used for swap) or a swap file, like we are creating in this tutorial.

Use the command: ‘swapon -s‘ In the output there is something like this:

Filename				Type		Size	Used	Priority
/dev/dm-0            partition	4159484	543024	-1

Another way to check your memory/swap is using the command ‘free‘. Execute the command: ‘free’ to check there is i.e. no swap at all. See field: Swap: X total -> 0

             total       used       free     shared    buffers     cached
Mem:        114404      83756      30648          0       2856      23460
-/+ buffers/cache:      57440      56964
Swap:            0          0          0

Remark: The examples to check the baseline are from different systems.

Create swap file

In this example, we will create a swap file of 512 MB.

sudo dd if=/dev/zero of=/tmp/swapfile bs=1M count=512
sudo chmod 600 /tmp/swapfile
sudo mkswap /tmp/swapfile

This will:

  • Create a file of 512 MB, filled with zeros.
  • Set the permissions of the file to read-write for root only. Otherwise other users can peek into the data of other users, stored in (cache) memory.
  • Create a swap file system on the newly created file.

Enable swap

Now it’s time to tell the system that we have a swap file available:

sudo swapon /tmp/swapfile

Check result

Check again using ‘swapon -s’

Filename				Type		Size	Used	Priority
/dev/dm-0             partition	4159484	542572	-1
/tmp/swapfile         file    	524284	0	-2

Besides of the original swap partition, we also see a swap file.  Mission accomplished!

Using the ‘free’ command (at the other system) we see:

             total       used       free     shared    buffers     cached
Mem:        114404      83756      30648          0       2856      23460
-/+ buffers/cache:      57440      56964
Swap:       524284          0     524284

As you can see at field: Swap: X total,  there is 524284 bytes swap space allocated.

Leave a comment