How to create swap space in Linux ?

Submitted by sysop on Thu, 05/25/2023 - 10:54

Swap space, also known as swap or swap area, is a concept in operating systems that provides virtual memory management. It is an area on a disk that is used to temporarily store data that cannot fit into the physical memory (RAM) of a computer. To set up swap space on Ubuntu, you can follow these steps:

  1. Check current swap usage: Run the following command to see if there is an existing swap space and its usage:
    sudo swapon --show
    This command will display the active swap devices or files.
     
  2. Create a swap file by running the following command:
    sudo fallocate -l <size> /swapfile
  3. Set the correct permissions on the swap file:
    sudo chmod 600 /swapfile
  4. Configure the swap using the swap file:
    sudo mkswap /swapfile
    
  5. Enable the swap: Activate the swap :
    sudo swapon /swapfile
  6. Verify the swap: Confirm that the swap is active and being used:
    sudo swapon --show

    This command should display the newly created swap device or file.

  7. Make the swap persistent: To ensure the swap remains active after a system reboot, you need to add an entry to the /etc/fstab file:

    Open the /etc/fstab file in a text editor:

    sudo nano /etc/fstab

    Add the following line at the end of the file for a swap file:

    /swapfile none swap sw 0 0
  8. Adjust swap settings (optional): If desired, you can modify the swap settings by editing the /etc/sysctl.conf file or adding a new configuration file in the /etc/sysctl.d/ directory. These settings allow you to control swap behavior, such as swappiness (the tendency to use swap ) and cache pressure.

    For example, to modify the swappiness value, open the /etc/sysctl.conf file and add or modify the following line:

    vm.swappiness=<value>
  9. Replace <value> with the desired swappiness value (0-100). A lower value (e.g., 10) makes the system less likely to use swap , while a higher.