SWAP

SWAP in file

  1. Create SWAP file at root with size 4GB:

    sudo dd if=/dev/zero of=/swapfile bs=1M count=4096
    sudo chmod 600 /swapfile
    sudo mkswap /swapfile
    
  2. Disable SWAP:

    sudo swapoff /swapfile
    # or disable all swap
    sudo swapoff -a
    
  3. Connect new SWAP file:

    sudo swapon /swapfile
    
  4. Add new SWAP to fstab (auto mount when system start):

    sudo echo "/swapfile swap swap defaults 0 0" | sudo tee -a /etc/fstab
    
  5. Optional. We will use the command sysctl to change settings dedicated to the Linux virtual memory manager vm.swappiness. This setting tells the Linux kernel/VM handler how likely it should be to use VM. It is a percent value, between 0 & 100. If you set this value to 0, the VM handler will be least likely to use any available swap space, and should use all available system memory first. If you set it to 100, the VM handler will be most likely to use available swap space and will try to leave a greater portion of system memory free for use. A value of 30% should be a happy medium between swapping and system memory:

    sudo sysctl -w vm.swappiness=30
    

Automated swapfile creation

#!/bin/bash

set -e

# SWAP file size in MB
SWAP_SIZE="1024"

# SWAP usage tunning
VM_SWAPPINESS="30"

SWAP_PATH="/swapfile"


# Create SWAP file at root
sudo dd if=/dev/zero of=$SWAP_PATH bs=1M count=$SWAP_SIZE
sudo chmod 600 $SWAP_PATH
sudo mkswap $SWAP_PATH

# Disable SWAP
sudo swapoff /swapfile

# Connect new SWAP file
sudo swapon $SWAP_PATH

# Add new SWAP to fstab (auto mount when system start)
sudo echo "$SWAP_PATH swap swap defaults 0 0" | sudo tee -a /etc/fstab

# Tweak system swap usage value
sudo sysctl -w vm.swappiness=$VM_SWAPPINESS