Set up swap virtual memory for Linux

This article takes centos7 as an example

First, it's simple#

We create a 2Gb file, then assign permissions, then set it as swap, and finally set it to be added permanently

However: Some methods I found online did not mention the need to assign permissions, which caused errors, so pay attention!#
[root@US002944879304 ~]# sudo mkswap /root/swapfile
mkswap: /root/swapfile: warning: wiping old swap signature.
Setting up swapspace version 1, size = 2097148 KiB
no label, UUID=d535b90d-f4f9-4246-a304-68a54537cc91

↑ Similar to this

Detailed commands#

To set up a 2GB swap partition in CentOS 7, follow these steps:

  1. Check the current swap situation:
    Enter the following command in the terminal to confirm the current system's swap situation:

    swapon --show
  2. Create a swap file:
    If there is not enough unallocated space in the system to create a new swap partition, you can create a swap file. First, create a 2GB file (assuming the file name is swapfile) using the following command:

    sudo fallocate -l 2G /swapfile

    If the fallocate command is not available, you can use the following command to create it:

    sudo dd if=/dev/zero of=/swapfile bs=1M count=2048
  3. Set file permissions:

    sudo chmod 600 /swapfile
  4. Convert the file to swap format:

    sudo mkswap /swapfile
  5. Enable the swap file:

    sudo swapon /swapfile
  6. Add the swap file permanently:
    You can use the echo command-line tool to append content to the /etc/fstab file, which avoids manual editing. Here is how to execute the sixth step in the command line:

echo '/swapfile   none    swap    sw    0   0' | sudo tee -a /etc/fstab
  1. Confirm that the swap is active:
    Re-run the swapon --show command to confirm that the new swap file is active.

By following the above steps, you should have successfully created a 2GB swap partition in CentOS 7.

Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.