Introduction
Swap space is to substitute disk space for RAM memory when RAM fills up. When the RAM is insufficient, idle pages are moved from the RAM to the swap space . The virtual memory contains physical memory and swap.
Approach 1:Create a Swapfile
Using this Approach can increase the swap space in a flexible way, and it can be easily removed when it is not needed. It is suitable for temporary needs or a situation increasing the swap space without stopping the server.
- Check the info about memory and swap
free -m
total used free shared buff/cache available
Mem: 7972 4822 160 487 2989 3175
Swap: 0 0 0
- Create a swapfile
Navigate to target directory(ex./mnt/resource) to create swapfile:
sudo dd if=/dev/zero of=/swapfile bs=1G count=5
The primary purpose of dd(data duplicator) command is to convert and copy files.if=<filename>:input file nameof=<filename>:output file namebs=<bytes>:Read and write BYTES bytes at a timecount=<N>:Copy only BLOCKS input blocks
- Change directory permissions
sudo chmod 600 /swapfile
- Create swap space
sudo mkswap /swapfile
Setting up swapspace version 1, size = 5 GiB (53687055024 bytes)
no label, UUID=ead1f.....
- Enable the swap file
You need to enable the swap file so that your system know it can use this file as swap.
sudo swapon /swapfile
- Vertify
free -m
- Disable files for swapping (When You Don’t Need This Swap File AnyMore)
sudo swapoff <swap>
- Enable swap from the next boot
Insert the following line in/etc/fstabfor swap from the next boot:<swapfile> none swap defaults 0 0
You can do it manualy or use the command line:
echo '/<swapfile> none swap fefaults 0 0' | sudo tee -a /etc/fstab
Approach 2 – Create swap partition
- Create a new partition
Please check out the article about Expand virtual hard disks on Linux VM - Format and create swap space
sudo mkswap /dev/sda2
※Warning:The mkswap command will format a partition for swap space.
- Enable the swap partition
sudo swapon /dev/sda2
- Verify
free -m
- Disable partitions for swapping (When You Don’t Need This Swap Partition AnyMore)
sudo swapoff <swap>
- Enable swap from the next boot
Insert the following line in/etc/fstabfor swap from the next boot:<swappartition> none swap defaults 0 0
You can do it manualy or use the command line:
echo ‘/<swappartition> none swap fefaults 0 0’ | sudo tee -a /etc/fstab