How to clear the Swap memory of a Linux server
Sometimes we may receive resource usage alerts indicating that the server's Swap or Exchange Memory is at 100% usage.
SERVICE ALERT: ce00000000000.dnssw.net
Unix Memory Nou
WARNING
Usage: real 95% (11404/11995 MB), buffer: 3 MB, cache: 302 MB, swap: 100% (1907/1907 MB)
This commonly happens in two scenarios:
- The server has run out of RAM and is or has been writing to Swap.
- The software installed on the server, due to its own configuration, is or has been writing to Swap.
danger ⚠️ The actions performed below may be dangerous if you do not have the necessary knowledge ⚠️
How to detect the alert
If you have Advanced Monitoring, you will have received an email notifying you of the Unix Memory Nou alert.
SERVICE ALERT: ce00000000000.dnssw.net
Unix Memory Nou
WARNING
Usage: real 95% (11404/11995 MB), buffer: 3 MB, cache: 302 MB, swap: 100% (1907/1907 MB)
How to handle the alert
To handle the alert, you must connect to your server via console. You can connect via the SWPanel Console [Handbuch: How do I access my Cloud using the console via SWPanel] or via SSH [Handbuch: Connect to your Cloud via console using PuTTY].
To clear the Swap memory, we must dump the data stored in the RAM memory.
First of all, we must check the state of the server's memory using the following command:
free -m
With this, we can see the memory bytes assigned, available, and used.
In this case, the server has 453B occupied and 1453B free:

We must ensure that the amount of Swap used is less than the amount of RAM available.
In this case, this rule is met; we have 453B of Swap in use and 3379B of RAM available:

danger ⚠️ Do not perform the following step if the previous rule is not met ⚠️
If the previous rule is met, we will proceed to dump the Swap into the RAM and, in this way, clear it. We will use the following command:
swapoff -a && swapon -a
When executing the command, the console will remain 'inactive' until the process finishes:

The process of clearing the Swap may take several minutes depending on the state of the server and its resources.
You can view the clearing process in real-time by opening another console and using the command:
watch -n0 free -m