If you need extra virtual memory on a Linux system without making a permanent change, you can create a swap file and enable it for the current session. This approach is straightforward and works well when you only need swap space temporarily.

Create a swap file

Use dd to create a file of the size you want. The example below creates a 2 GB swap file:

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048
  • bs=1M means the command reads and writes in 1 MB blocks.
  • count=2048 means it writes 2048 blocks in total, which equals 2 GB (1M × 2048 = 2048MB = 2GB).

Restrict the file permissions

The swap file should only be readable and writable by root:

sudo chmod 600 /swapfile

This is an important security step before enabling the file as swap.

Format the file for swap

Once the file has been created, initialize it as swap space:

sudo mkswap /swapfile

Enable the swap file

Activate it with swapon:

sudo swapon /swapfile

At this point, the system can start using the file as swap.

Check whether it is active

You can confirm that the swap space was enabled successfully with either of these commands:

swapon --show
free -h

swapon --show lists active swap devices and files, while free -h gives a readable overview of memory and swap usage.

Important note about temporary swap

This method only enables swap temporarily. After a reboot, the swap file will no longer be active. If you want the system to keep using it after restart, you need to add the appropriate configuration to /etc/fstab.

Disable the swap file

When you no longer need the temporary swap space, turn it off with:

sudo swapoff /swapfile

If you need a larger swap file

To create more swap space, adjust the count value in the dd command. For example, this creates a 4 GB swap file:

sudo dd if=/dev/zero of=/swapfile bs=1M count=4096

The rest of the process stays the same: set permissions, run mkswap, and then enable it with swapon.