Typically, FreeBSD cloud servers do not come with a swap file (virtual memory) set up by default. In testing environments, we generally do not need to pay attention to swap, but in production environments, understanding the workings of swap files is essential. When an application starts consuming a large amount of memory, swap provides additional memory space to prevent system overloads. Even under normal circumstances, FreeBSD employs proactive memory management. For example, memory occupied by continuously running applications is swapped out to a swap file, freeing up more memory for more useful programs, such as file system caches. Operating systems without swap can lead to unpredictable issues, and even high-specification cloud servers require the setup of a swap file.
1.Verify the Status of the Swap File
Before setting it up, confirm that there is no existing swap file. The return result of swapinfo should be empty.
# swapinfo
Device 1K-blocks Used Avail Capacity
2.Create the Swap File
Before creating a swap file, first decide on its size. The traditional approach is one, two, or five times the size of the memory, but this rule no longer applies in cloud servers. For instance, a cloud server with 16GB of memory does not necessarily need 32GB of disk space for a swap file. Therefore, there is no specific standard for the size of a swap file, and its size can be modified at any time. This is especially true when using SSDs, as changing the size of the swap file has a negligible impact on disk IO.
In this example, we will create a 512MB swap file at the path /usr/swap0, but you can adjust the size and path of the swap file as needed. Execute the following script as root.
dd if=/dev/zero of=/usr/swap0 bs=1m count=512
chmod 0600 /usr/swap0
echo "md99 none swap sw,file=/usr/swap0,late 0 0" >> /etc/fstab
swapon -aL
The script first creates a swap file using the dd command, then adds a line in /etc/fstab to tell the operating system to load the swap at boot. The command swapon -aL instructs the operating system to activate all swap partitions listed in fstab. When the FreeBSD system boots, the swap file will be loaded normally.
3.Confirm the Success of the Swap File Creation
Still using the swapinfo command, check the status of the swap file. If the return result is as expected, it indicates a successful creation.
# swapinfo
Device 1K-blocks Used Avail Capacity
/dev/md99 524288 0 524288 0%
23-02-2024 02:02:07
22-02-2024 03:19:32
22-02-2024 03:16:03
22-02-2024 03:14:03
22-02-2024 03:11:58