How to Set Up Swap on a Linux Cloud Server?

16-01-2024 02:30:08

At times, our servers may encounter insufficient memory, often due to certain applications suddenly consuming a large amount of memory. The most direct way to address this issue is to increase the server's memory, though this incurs additional costs. An alternative is to use virtual memory, also known as swap, a technique that utilizes part of the hard disk space to store temporary data. The following article introduces how to set up swap, applicable to Linux operating systems like CentOS, Ubuntu, Debian, etc.

Step 1: Check the Status of Swap

Use the following command to view the memory situation:

free -m

If the result shows swap as 0, it indicates that swap does not exist, and you need to create swap.

total              used       free     shared    buffers     cached
Mem:               1840       1614     226       15          36       1340
-/+ buffers/cache:            238      1602
Swap:              0          0        0

Alternatively, you can use this command to check. If no output is generated, it means swap does not exist.

swapon -s

Step 2: Create Swap

We use the following command to create a swap file of 2GB.

dd if=/dev/zero of=/swapfile count=2048 bs=1M

The output is as follows:

2048+0 records in
2048+0 records out
2147483648 bytes (2.1 GB) copied, 10.5356 s, 204 MB/s

Step 3: Activate Swap

Swap is not automatically recognized by default, and we need to set the appropriate permissions for it to be usable. Execute the following command to set the swap file's permissions to 600, which means readable and writable for the root user.

chmod 600 /swapfile

Activate swap:

mkswap /swapfile

The output is as follows:

Setting up swapspace version 1, size = 2097148 KiB
no label, UUID=ff3fc469-9c4b-4913-b653-ec53d6460d0e

Step 4: Enable Swap

Execute the following command to enable swap:

swapon /swapfile

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

vi /etc/fstab

Add the following code at the end:

/swapfile   none    swap    sw    0   0

Save with the :wq command, and swap will start with the system.

Finally, we can confirm if swap is set up successfully using the free command.

free -m

The output is as follows. You can see that swap is no longer 0, indicating that swap has been successfully set up.

total       used       free     shared    buffers     cached
Mem:          1840       1754         86         16         23       1519
-/+ buffers/cache:        210       1630
Swap:         2047          0       2047

This concludes the method for setting up swap on a Linux cloud server.