Swap space is a technology that allows a computer to use disk space when the RAM is insufficient, helping to maintain system stability. This article outlines the steps to create and manage swap space on Ubuntu servers.
To check if your Ubuntu system already has swap space:
sudo swapon --show
If the output is empty, your system does not have any configured swap space. To view detailed RAM and swap information, use:
free -h
Follow these steps to create a new swap file:
Decide how much swap space you need. For example, to create 4 GB of swap space:
sudo fallocate -l 4G /swapfile
Alternatively, you can use the dd
command:
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096
Restrict access to the swap file so that only the root user can access it:
sudo chmod 600 /swapfile
Format the file as swap space:
sudo mkswap /swapfile
Activate the swap file:
sudo swapon /swapfile
Check that the swap space is active:
sudo swapon --show
or
free -h
To ensure the swap space remains available after a reboot, add it to the /etc/fstab
file:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
You can optimize swap usage by adjusting the swappiness value, which controls how aggressively the system uses swap space:
To temporarily change the swappiness value:
sudo sysctl vm.swappiness=10
To make this change permanent, add the following line to the /etc/sysctl.conf
file:
vm.swappiness=10
To monitor the usage of swap space, use the following commands:
free -m
or
top
Creating and optimizing swap space on Ubuntu ensures better system stability during memory shortages. By following the steps above, you can easily set up swap space and enhance your system’s performance.
If you have any questions or feedback, feel free to contact us!