Change swap size in Ubuntu

Starting with Ubuntu 17.04, the swap partition is replaced with a swap file, which makes it easy to be resized.

NOTE: Most of the commands below will require root privilege.

You can check your current swap size with

swapon -s

or

free -h

By default, the swapfile is /swapfile with file mode 600 and it belongs to the root user.

ls -lh /swapfile

If you want to resize your swapfile, it’s simple. The steps are

  1. Disable the current swap file:

    swapoff -a
    
  2. Change the size of the swap file. There are two possible ways, you can choose either of them

    1. Use the command dd

      dd if=/dev/zero of=/swapfile bs=1M count=4096
      

      This will allocate 4GB in total(each block is 1MB and there are 4096 blocks) to /swapfile.

    2. Use the command fallocate

      fallocate -l 4G /swapfile
      

      This will also allocate 4GB to /swapfile.

  3. Make sure the file mode is 600 by

    chmod 600 /swapfile
    

    The output of ls -lh /swapfile should be like

    -rw------- 1 root root 4G May 23 19:48 /swapfile
    
  4. Make the newly created swap file useable by

    mkswap /swapfile
    
  5. Activate the swap file

    swapon /swapfile
    
  6. Add swap setting to your /etc/fstab by adding(if this line does not exist) this line

    /swapfile none swap sw 0 0
    

If you want to disable the swap file in your system, it’s also very simple.

  1. Disable the swap

    swapoff -v /swapfile
    
  2. Delete(or comment) the swap line in /etc/fstab

    /swapfile none swap sw 0 0
    
  3. Remove the actual swap file

    rm -v /swapfile
    
Chao Cheng
Chao Cheng
Statistician

My research interests include applied statistics and machine learning.

Related