How to add a swap file on a VPS

To begin with, before creating a swap file, it is advisable to check the list of mounted partitions and their size. To do this, execute the df -h command.

In this example, a swap file will be created in the /var directory with a size of 4GB.

Creating a swap file

Create an empty file and set the correct permissions:

[wpcm lang="bash"]sudo touch /var/.swap.img sudo chmod 600 /var/.swap.img[/wpcm]

Fill the file with zeros to the desired size (4GB in this example):

[wpcm lang="bash"]sudo dd if=/dev/zero of=/var/.swap.img bs=1024k count=4096[/wpcm]

Format the swap file as swap space:

[wpcm lang="bash"]sudo mkswap /var/.swap.img[/wpcm]

Activate the swap file:

[wpcm lang="bash"]sudo swapon /var/.swap.img[/wpcm]

To make the swap file persistent across reboots, add it to the /etc/fstab file:

[wpcm lang="bash"]sudo echo "/var/.swap.img none swap sw 0 0" >> /etc/fstab[/wpcm]

Verify that the swap file is active and working correctly:

[wpcm lang="bash"]free -h[/wpcm]

or

[wpcm lang="bash"]swapon --show[/wpcm]

The swap file will now provide additional virtual memory to your system, which can be beneficial for managing memory-intensive tasks.

Рейтинг: 1 Star2 Stars3 Stars4 Stars5 Stars (1 оцінок, сер. 5.00)
Loading...