13.4. Creating a swap file
Set up a swap file to provide virtual memory that prevents system crashes when physical RAM becomes full. This solution is particularly useful when you need additional swap space without repartitioning disks or modifying existing storage configurations.
Prerequisites
- You have enough disk space.
Procedure
- Determine the size of the new swap file in megabytes and multiply by 1024 to determine the number of blocks. For example, the number of 1024-byte sized blocks required for a 64 MB file is 65536.
Create an empty file:
# dd if=/dev/zero of=/swapfile bs=1024 count=65536Replace 65536 with the value equal to the required block size.
Set up the swap file with the command:
# mkswap /swapfileChange the security of the swap file so it is not world readable.
# chmod 0600 /swapfileEdit the
/etc/fstabfile with the following entries to enable the swap file at boot time:/swapfile none swap defaults 0 0The next time the system boots, it activates the new swap file.
Regenerate mount units so that your system registers the new
/etc/fstabconfiguration:# systemctl daemon-reloadActivate the swap file immediately:
# swapon /swapfile
Verification
To test if the new swap file was successfully created and activated, inspect active swap space by using the following command:
$ cat /proc/swaps$ free -h