In the use of cloud servers, there are times when we need to enhance system performance and prevent situations of insufficient memory. Memory shortage is usually caused by certain applications requiring a large amount of memory. Swap, also known as virtual memory, is a technology that utilizes hard disk capacity as memory. This tutorial explains how to set up a swap file in the Linux operating system, applicable to operating systems like CentOS, Fedora, Ubuntu, Debian, etc. It should also be applicable to other Linux operating systems.
1.Verify the Existence of a Swap File
First, we need to confirm the current active status of the swap file, using the following command.
# free -m
total used free shared buffers cached
Mem: 1840 1614 226 15 36 1340
-/+ buffers/cache: 238 1602
Swap: 0 0 0
If all the values in the swap line are 0, you can proceed to the next step. Alternatively, you can execute the following command; if there is no output, it also indicates that the swap file does not exist, and you can continue to the next step.
swapon -s
2.Create a Swap File
Typically, the storage path for the swap file is in the root directory of the operating system. For example, to create a 2GB swap file, execute the following command.
# dd if=/dev/zero of=/swapfile count=2048 bs=1M
2048+0 records in
2048+0 records out
2147483648 bytes (2.1 GB) copied, 10.5356 s, 204 MB/s
Verify whether it was created successfully. If the name of the swap file appears, it indicates successful creation.
ls / | grep swapfile
3.Activate the Swap File
After creating a swap file, it won't activate automatically. We need to instruct the operating system to enable and activate the swap file.
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
Reconfirm whether the swap file has been activated successfully:
# free -m
total used free shared buffers cached
Mem: 1840 1754 86 16 23 1519
-/+ buffers/cache: 210 1630
Swap: 2047 0 2047
If the values in the swap line are not 0, it indicates that the swap file has been successfully activated.
4.Load Swap on System Boot
By default, the operating system will not load the swap file on startup. To load swap on system boot, you need to modify the /etc/fstab file.
nano /etc/fstab
Add the following content at the end of the file.
/swapfile none swap sw 0 0
5.Expand the Swap File
If the swap file has been successfully created, you can execute the following command to expand it. Assuming the swap file name is /swapfile, expand by 1024MB.
swapoff /swapfile
dd if=/dev/zero of=/swapfile bs=1M count=1024 oflag=append conv=notrunc
mkswap /swapfile
swapon /swapfile
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