Creating a Swap File

  1. Use the dd command to create a file of the required size, for example, one million 1KB blocks.

    sudo dd if=/dev/zero of=/swapfile bs=1024 count=1000000
    1000000+0 records in
    1000000+0 records out
    1024000000 bytes (1.0 GB, 977 MiB) copied, 6.10298 s, 168 MB/s
  2. Initialize the file as a swap file.

    sudo mkswap /swapfile
    mkswap: /swapfile: insecure permissions 0644, fix with: chmod 0600 /swapfile
    Setting up swapspace version 1, size = 976.6 MiB (1023995904 bytes)
    no label, UUID=43964855-e81f-414c-a61c-370408085ba4
  3. Change the permissions on the file so that it is not world readable.

    sudo chmod 0600 /swapfile
  4. Add an entry to the /etc/fstab file so that the system uses the swap file at system reboots, for example:

    /swapfile       swap       swap       defaults       0 0
  5. Regenerate the mount units and register the new configuration in /etc/fstab.

    sudo systemctl daemon-reload
  6. Activate the swap file.

    sudo swapon /swapfile
  7. (Optional) Test whether the new swap file was successfully created by inspecting the active swap space:

    cat /proc/swaps
    sudo free -h