Sunday, December 21, 2014

How to create a swap file

Linux can be configured to use swap space, aka secondary disk storage, when physical memory is running low. Swap spaces can be allocated as disk partitions ('swap partitions') or as files ('swap files'). While swap partitions are generally preferred over swap files, if your system is a virtual private server (VPS) without a pre-configured swap partition, creating a swap file may be your only option. The following procedure describes how to create a swap file.

List swap spaces

Before you create a swap file, you should first check whether the system has any swap space pre-allocated. The easiest way is to run the free command.

$ free -h total used free shared buffers cached Mem: 497M 490M 6.2M 0B 14M 101M -/+ buffers/cache: 375M 121M Swap: 0B 0B 0B

The line labeled Swap above tells you that there is no swap space configured.

Alternatively, run the swapon command with the -s parameter:

$ sudo swapon -s Filename Type Size Used Priority

I prefer free because root privilege is not required to run the command.

Create swap file

Follow the steps below to create and activate a swap file.

  1. Create a new file pre-allocated with the desired file size.
    $ sudo fallocate -l 500M /var/swap.img

    The above command pre-allocates 500 megabytes for the file /var/swap.img.

  2. Secure the new file.
    $ sudo chmod 600 /var/swap.img
  3. Make a swap file.

    The following mkswap command sets up /var/swap.img as a swap file.

    $ sudo mkswap /var/swap.img Setting up swapspace version 1, size = 511996 KiB no label, UUID=a0a90414-adab-4c50-8b27-0d27f0c34448
  4. Activate the swap file.
    $ sudo swapon /var/swap.img

    After executing the above swapon command, verify that the swap file is indeed enabled.

    $ free -h total used free shared buffers cached Mem: 497M 464M 32M 0B 14M 104M -/+ buffers/cache: 346M 151M Swap: 499M 34M 465M $ sudo swapon -s Filename Type Size Used Priority /var/swap.img file 511996 35184 -1

    According to the above output, the swap file has been enabled. However, unless you complete the next step, the swap file will be disabled when you reboot the machine.

  5. Update file system table.

    Add the swap file to the file system table using the following command:

    $ sudo sh -c 'echo "/var/swap.img none swap sw 0 0" >> /etc/fstab'

No comments: