How to Set Up Swap on a FreeBSD Cloud Server?

17-01-2024 02:38:46

Swap is known for its role as an extension and exchange medium for physical memory. By default, cloud servers do not enable swap due to its consumption of disk I/O, which can reduce disk performance. However, for operating systems running applications that consume a large amount of memory, enabling swap is essential. Once enabled, long-term idle memory can be swapped to the swap partition, freeing up valuable memory for more frequently updated applications, such as file caching. Since FreeBSD systems differ from other Linux operating systems in swap settings, this article specifically explains how to set up swap on FreeBSD systems.

Step One: Confirm the Status of Swap

Execute the following command; if there is no output, it means swap does not exist and needs to be created.

swapinfo

Regarding the size of swap, the old rule of thumb was to have swap size equal to one or two times the size of the memory. However, as memory sizes have increased, this rule no longer applies. For instance, a system with 16GB of memory often does not require a 32GB swap. Therefore, the appropriate size of swap should be determined based on different scenarios. Moreover, swap size is not fixed and can be adjusted as needed. Furthermore, with the widespread adoption of SSDs, swap does not significantly impact disk performance.

Step Two: Create Swap

As an example, we will create a 512MB swap file at the path /usr/swap0. These two parameters can be adjusted according to specific circumstances.

dd if=/dev/zero of=/usr/swap0 bs=1m count=512

Set the permissions of the swap file to 600, making it readable and writable by the root user.

chmod 600 /swapfile

Step Three: Enable Swap

By default, swap does not automatically start with the system, so it needs to be written into the file system.

echo "md99 none swap sw,file=/usr/swap0,late 0 0" >> /etc/fstab
swapon -aL

Use the swapinfo command again to confirm the success of the swap setup.

swapinfo

If the output is as expected, it indicates that the swap has been successfully set up.

Device          1K-blocks     Used    Avail Capacity
/dev/md99          524288        0   524288     0%

This is the method for setting up swap on a FreeBSD cloud server.