Add a Swap File

When you’re running on a Linux System (or any Unix Operating System), it’s common to use a swap to complete and optimize the memory usage on the computer (especially for older ones). There are different ways to do that, you can:

  • Create a swap on a full partition system (most of Linux distribution will allow you to create it when installing the system or later using fdisk commands to create partition and activate it by following the same steps than below from #2)
  • Create a swap file later on any partition and activate it directly using command-line

I will present here the second case: the creation of a swap file (you will need to get root rights to perform most of the following commands).

  1. Create a file with dd command to create a 1024MB empty file (which will be used by swap).
    dd if=/dev/zero of=/swap1 bs=1024 count=1048576

    We are here writing a file of 1024*1024MB=1048576 blocks size with a Read/Write of 1024 bytes at a time.

  2. Now format the file to swap format
    mkswap /swap1
  3. Ensure that the rights access are correct on this file (for security purposes)
    chown root:root /swap1
    chmod 0600 /swap1
  4. Now activate swap on your file
    swapon /swap1
  5. To deactivate swap on your file, juste use the following command
    swapoff /swap1

You can now check your swap availability by using the top or free -m command.

Right now, you probably want this swap file to be mounted and activated automatically at the system startup to avoid to perform these steps manually each time ? No problem, juste edit the /etc/fstab file and add this following line:

/swap1 swap swap defaults 0 0

Your system has now a swap file ready to use !


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *