How to create Linux's swap swap partition file method steps
- 2021-01-03 21:14:14
- OfStack
Swap profile
In Linux, Swap (i.e., swap partition), similar to Windows's virtual memory, is when the memory is not enough, 1 part of the hard disk space virtual memory use, so as to solve the problem of insufficient memory capacity.
How do I create an Swap file
1. Create 1 file to swap
sudo fallocate -l 1G /swapfile
If faillocate is not installed or you receive an error message, fallocate failed: Operation not supported can create an interchange file using the following command:
sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576
2. Set the right permissions
Only root users can write and read swap files. Set the correct permissions type:
sudo chmod 600 /swapfile
3. Set up the Linux swap area
Use the mkswap utility to set the file to the Linux swap area:
sudo mkswap /swapfile
4. Enable switching
Activate the interchange file using the following command:
sudo swapon /swapfile
To make the change permanently open the /etc/fstab file and attach the following lines:
/swapfile swap swap defaults 0 0
5. Verify the switching status
To verify that the exchange is active, we can use the swapon or free commands as follows:
sudo swapon --show
The output
NAME TYPE SIZE USED PRIO
/swapfile file 1024M 507.4M -1
sudo free -h
The output
total used free shared buff/cache available
Mem: 488M 158M 83M 2.3M 246M 217M
Swap: 1.0G 506M 517M
How to adjust swappiness
Swappiness is an Linux kernel attribute that defines how often the system uses swap space. Swappiness can have values between 0 and 100. A lower value will enable the kernel to avoid swapping as much as possible, while a higher value will enable the kernel to use swap space more actively.
The default swappiness value is 60. You can check the current swappiness value by typing the following command:
sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576
0
The output
[
60
While the desktop can use the swappiness value of 60, you may need to set a lower value for the production server.
For example, to set the swappiness value to 10, type:
sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576
1
To keep this parameter unchanged after reboot, append the following lines to the /etc/ sysctl.conf file:
sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576
2
The optimal swappiness value depends on your system workload and how memory is used. You should adjust this parameter in small increments to find the best value.
How do I delete the swap file
If you want to deactivate and delete the swap file for any reason, follow these steps:
1. First, deactivate the exchange using the following command:
sudo swapoff -v /swapfile
2. Delete swap file entry /swapfile swap swap defaults 0 0 from /etc/fstab file.
3. Finally, delete the actual swapfile file:
sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576
4