Ubuntu – The swap area is set to zero in Ubuntu Server 18.04.2

swap

By checking the swap size in my Ubuntu server I observed that is set to zero. Since it was installed in very basic configuration from AWS EC2, I'm not sure if I had to do additional steps to adjust swap size area.

I run the following commands and got the below results :

    # grep Swap /proc/meminfo
       SwapCached:            0 kB
       SwapTotal:             0 kB
       SwapFree:              0 kB

    # swapon -s 

    #  free -m
                     total        used        free      shared  buff/cache   available
    Mem:           7975         187        7059           0         728        7549
    Swap:             0           0           0

# cat /proc/swaps
  Filename                         Type            Size    Used    Priority

Is it normal to have a swap area set to zero ? If it is not, what should I do to fix it ?

Thanks !

Best Answer

For some reason, some cloud (VPS) providers disable the swap in their (modified) installations. Nowadays Ubuntu support swap file, thus you do not need a separate partition for swap. To enable the swap via swap file follow these steps:

sudo fallocate -l 4G /swapfile  # Create a 'swap-file'; 4G in this case
sudo chmod 600 /swapfile        # Set the necessary file permissions
ls -lh /swapfile                # Check
sudo mkswap /swapfile           # Mark the file as 'swap'
sudo swapon /swapfile           # Enable the 'swap'
sudo swapon --show              # Check
free -h                         # Another check

Edit /etc/fstab and make the changes permanent. Use these commands to do the changes:

sudo sed 's/^.*swap.*$//' /etc/fstab -i.bak                # Remove the previous swap entries 
                                                           # and create a backup copy of the file
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab # Add a new entry

Or edit /etc/fstab and add the the following entry manually:

/swapfile none swap sw 0 0

That is it.


Ideas for additional tweaks (I would prefer to use the default settings for normal swap usage):

  • Change the frequency of RAM to SWAP data copy:

    sudo sysctl vm.swappiness=10    # value 0-100: low value low frequency
    cat /proc/sys/vm/swappiness     # Check
    
  • Change the frequency of Cache flush:

    sudo sysctl vm.vfs_cache_pressure=50 # 0-100: high value high frequency
    cat /proc/sys/vm/vfs_cache_pressure  # Check
    
  • Make the above changes permanent:

    sudo cp /etc/sysctl.conf{,.bak} # Create a backup copy of the file '/etc/sysctl.conf'
    echo -e '\nCustom settings: value 0-100; default 100\nvm.swappiness=10\nvm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf
    

    Or edit /etc/sysctl.conf and add the the following entries manually:

    # Custom settings: value 0-100; default 100
    vm.swappiness=10
    vm.vfs_cache_pressure=50
    
Related Question