How to Add a Swap File in Linux

November 09, 2005
Manually creating a Swap file in Linux is easy and can be accomplished by a few steps as shown below.

1. Create a swap file of the desired size


We use the dd command to create and copy the file we will be using as the swap file.

As an example, lets create a swap file of 1 GB size -

# dd if=/dev/zero of=/my-swap-file bs=1024 count=1024000

The options passed to the dd command are as follows -

if=/dev/zero - Says to read from /dev/zero instead of stdin.

of=/my-swap-file - Asks the command to write the output to the file /my-swap-file.

bs=1024 -  Block size, read and write up to 1024 bytes at a time. The optimum block size is hardware dependent but 512 to 1024 is a fair value to use.

count=1024000 - Copy only 1024000 input blocks;  [1024 * 1000 MB]

2. Set the correct permission for the swap file


# chown 600 /my-swap-file

Make the permissions read and write for owner and no permissions for group and others. For security reasons, it is prudent to restrict access to the swap file to people with adminstrative powers - usually root.

3. Prepare the swap file


For this you use the mkswap command.

# mkswap /my-swap-file

4. Activate the swap file


Use the swapon command to activate the swap file so the system can start using it.

# swapon /my-swap-file

Finally, if you want the swap file to be available across reboots, you need to append the following line to the /etc/fstab file.

/my-swap-file  swap  swap  defaults  0  0

The above line tells Linux to mount the swap file during boot time.

Save and close the /etc/fstab file.



1 comments:

  • Looks good but try 'dd bs=1M count=64' instead. It uses 1 MB of memory while dd is running, but most people have 1MB to spare. Makes the numbers simpler when you get into the multi-GB range.