196

Is there a way to increase my existing "swapfile" without having to destroy and re-create it? I would like to up my swap space from 1GB to 2GB. Currently it is set up as such:

$ sudo swapon -s
Filename                Type        Size    Used    Priority
/swapfile               file        1048572 736640  -1
$ ls -lh /swapfile
-rw------- 1 root root 1.0G Nov  9  2016 /swapfile

I'm using Ubuntu 14.04.

muru
  • 207,228
Dave
  • 2,315

6 Answers6

245

First disable swap file:

sudo swapoff /swapfile

Now let's increase the size of swap file:

sudo dd if=/dev/zero of=/swapfile bs=1M count=1024 oflag=append conv=notrunc

The above command will append 1GiB of zero bytes at the end of your swap file.

Setup the file as a "swap file":

sudo mkswap /swapfile

enable swaping:

sudo swapon /swapfile

On a production system, if your operating system does not let you to disable the swap file using sudo swapoff /swapfile and you receive a messages similar to:

swapoff failed: Cannot allocate memory

Then You might consider having multiple swap files or create a new larger one, initialize it and then remove the old smaller one.

Ravexina
  • 57,256
127

You should add a new swapfile instead of resizing the existing one because it costs you nothing to do so. To resize a swapfile, you must first disable it, which evicts the swap contents to RAM, which increases pressure on RAM and may even summon the OOM killer (not to mention that you could possibly be thrashing your disks for several minutes). Multiple swap files are not a problem, it's trivially easy to setup yet another swap file. There's quite literally no benefit to resizing a swap file over adding another.

dd if=/dev/zero of=/some/file count=1K bs=1M
mkswap /some/file
sudo chown root:root /some/file
sudo chmod 600 /some/file
sudo swapon /some/file

This dd command creates a file of size 1 gigabyte. count is the size of the file in block size, which is set by the bs flag, in bytes. Here, bs is set to 1M (= 2^20 bytes, 1 megabyte (MiB)), when multiplied by 1K ( = 1024) is 1 GiB (1 gigabyte).

wjandrea
  • 14,504
muru
  • 207,228
54

I have tested this answer on all LTS versions of Ubuntu from 14.04 LTS through 22.04 LTS, inclusive, all with an ext4 filesystem.

Notes about fallocate vs dd

Before we continue, I want to point out that some answers use fallocate to allocate space for a file, instead of dd. Don't do that. Use dd. @muru pointed out some important points here and here. Although fallocate is much much faster, it may create files with holes. I think that simply means the space is not contiguous, which is bad for swap files. I picture this as meaning that fallocate creates a C-style linked-list of memory, whereas dd creates a C-array contiguous block of memory. Swap files need a contiguous block. dd does this by doing a byte-for-byte copy of binary zeros from the /dev/zero pseudo-file into a new file it generates.

man swapon also states not to use fallocate, and to use dd instead. Here is the quote (emphasis added):

NOTES

You should not use swapon on a file with holes. This can be seen in the system log as

swapon: swapfile has holes.

The swap file implementation in the kernel expects to be able to write to the file directly, without the assistance of the filesystem. This is a problem on preallocated files (e.g. fallocate(1)) on filesystems like XFS or ext4, and on copy-on-write filesystems like btrfs.

It is recommended to use dd(1) and /dev/zero to avoid holes on XFS and ext4.

And from man mkswap (emphasis added):

Note that a swap file must not contain any holes. Using cp(1) to create the file is not acceptable. Neither is use of fallocate(1) on file systems that support preallocated files, such as XFS or ext4, or on copy-on-write filesystems like btrfs. It is recommended to use dd(1) and /dev/zero in these cases. Please read notes from swapon(8) before adding a swap file to copy-on-write filesystems.

So, use dd, not fallocate, to create the swap files.

Update 17 June 2024: with swapon --version swapon from util-linux 2.37.2 on Ubuntu 22.04, man swapon still says (emphasis added):

Preallocated files created by fallocate(1) may be interpreted as files with holes too depending of the filesystem. Preallocated swap files are supported on XFS since Linux 4.18.

The most portable solution to create a swap file is to use dd(1) and /dev/zero.

So, to be most portable, I'll continue to recommend the dd technique as shown below, even though modern fallocate on some filesystems may work just fine and not create holes.

Option 1 (my preference): delete the old swap file and create a new one of the correct size:

Rather than resizing the swap file, just delete it and create a new one at the appropriate size!

swapon --show               # see what swap files you have active
sudo swapoff /swapfile      # disable /swapfile
# Create a new 16 GiB swap file in its place (could lock up your computer 
# for a few minutes if using a spinning Hard Disk Drive [HDD], so be patient)
# (Ex: on 15 May 2023, this took 3 min 3 sec on a 5400 RPM 750 GB 
# model HGST HTS541075A9E680 SATA 2.6, 3.0Gb/s HDD in an old laptop of mine)
time sudo dd if=/dev/zero of=/swapfile count=16 bs=1G
sudo mkswap /swapfile       # turn this new file into swap space
sudo chmod 0600 /swapfile   # only let root read from/write to it, for security
sudo swapon /swapfile       # enable it
swapon --show               # ensure it is now active

In case you are adding this swap file for the first time, ensure it is in your /etc/fstab file to make the swap file available again after each reboot. Just run these two commands in your terminal:

# Make a backup copy of your /etc/fstab file just in case you
# make any mistakes
sudo cp /etc/fstab /etc/fstab.bak

(Run this command in your terminal, too). This adds a swapfile entry

to the end of your /etc/fstab File System Table file to re-enable

the swap file after each boot

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

View the /etc/fstab file to ensure the swapfile entry was added to the

end. You should see this at the end of the output:

```

/swapfile none swap sw 0 0

```

cat /etc/fstab

Source: see the "Step 4: Make the changes permanent" section here.

For a detailed description of what the 6 fields (columns) in the /etc/fstab file mean, see:

man fstab

Or, view it online here: https://man7.org/linux/man-pages/man5/fstab.5.html.

For the meaning of sw in the fourth field of the /etc/fstab file, on BSD systems it means swapon, and on Linux it means nothing at all and is not documented anywhere, but acts as a "cargo-culted" superstitious and meaningless placeholder for historical reasons. Since having it there ensures this fstab (Filesystem Table) entry is compatible with BSD systems, and since it won't break Linux systems, it's a good idea to include it for maximum compatibility. I posted this here too.

Option 2: resize the old swap file:

The accepted answer by @Ravexina is correct. However, initially I didn't understand all of its pieces, so I wanted to include some more descriptions and explain more of the details. See dd --help and man dd. Some of my learning on this comes from Bogdan Cornianu's blog post as well. I also add a few commands at the end to show how to verify your swap space once you create it.

How to resize swap file:

Here we will increase the size of the existing swap file by writing 8 GiB (Gibibytes) of zeros to the end of it.

  1. Turn off usage of just this one swap file (located at "/swapfile"):

     # Do this
     sudo swapoff /swapfile
    

    NOT this, which unnecessarily disables all swap files or partitions

    sudo swapoff --all

    or

    sudo swapoff -a

  2. Increase the size of the swap file by 8 GiB by appending all zero bytes to the end of it (rather than rewriting the whole file, which would be slower):

     sudo dd if=/dev/zero of=/swapfile bs=1G count=8 oflag=append conv=notrunc
    
    • if = input file

    • /dev/zero = a special Linux "file" which just outputs all zero bytes every time you read from it

    • of = output file

    • bs = block size

      • Here, 1G stands for 1 Gibibyte, or GiB, which is the base-2 version of "Gigabyte, which is base-10. According to man dd, G =1024*1024*1024 bytes. This is how I like to size files since computers and hardware memory are base-2.
      • If you'd like to use 1 Gigabyte, or GB, which is the base-10 version of "Gibibyte", which is base-2, then you must instead use 1GB rather than 1G. man dd shows that GB =1000*1000*1000 bytes.
    • count = multiplier of blocks; the total memory written will be count * bs.

    • oflag=append means to append to the end of the output file, rather than rewriting the whole thing. See dd --help and man dd. From dd --help:

      append    append mode (makes sense only for output; conv=notrunc suggested)
      
    • conv=notrunc means when "converting" the file, "do not truncate the output file"; dd --help, as you can see just above, shows this is recomended whenever doing oflag=append

    • Note: if you wanted to rewrite the whole swap file rather than just appending to it, you could create a 32 GiB swapfile like this, for example:

        sudo dd if=/dev/zero of=/swapfile bs=1G count=32
      
  3. Make the file usable as swap

     sudo mkswap /swapfile
    
  4. Turn on the swap file

     sudo swapon /swapfile
    
  5. (Bonus/Optional): ensure this swap file you just created is now in usage:

     swapon --show
    

    Sample output:

    $ swapon --show
    NAME      TYPE SIZE USED PRIO
    /swapfile file  64G 1.8G   -2
    

    You can also look at some memory/swap info with these two commands as well:

     # 1. Examine the /proc/meminfo file for entries named "swap", such 
     # as the "SwapTotal" line
     cat /proc/meminfo | grep -B 1000 -A 1000 -i swap
    

    2. Look at total memory (RAM) and swap (virtual memory) used

    and free:

    free -h

References:

  1. @Ravexina's answer
  2. Bogdan Cornianu's blog post here: https://bogdancornianu.com/change-swap-size-in-ubuntu/
  3. "How to Create and Use Swap File on Linux": https://itsfoss.com/create-swap-file-linux/

See also:

  1. My answer where I use the above information about increasing your swapfile size in order to solve an out-of-memory Bazel build error: Stack Overflow: java.lang.OutOfMemoryError when running bazel build
  2. My answer: Unix & Linux: What 'sw' means in the fstab swap entry for 'mount options' column
Gabriel Staples
  • 11,502
  • 14
  • 97
  • 142
31

You can create another swap file as i did:

  1. sudo fallocate -l 4G /swapfile
  2. sudo chmod 600 /swapfile
  3. sudo mkswap /swapfile
  4. sudo swapon /swapfile
  5. Verify it is working with sudo swapon --show
    To make it permanent add a file to the fstabfile typing:
    echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
borekon
  • 421
6

I have good results on my Ubuntu 17.04 following the advice of Arian Acosta from the blogpost. One can substitute the 4G here sudo fallocate -l 4G /swapfile with any amount of gigabytes you want. For example sudo fallocate -l 2G /swapfile for TS.

Generally speaking, the recommended size for a swap file is 2X the amount of RAM, but you can make it as big as you need. Remember that this is not a substitute for memory because performance is much worse since things are stored in the disk.

I’ve created a simple bash script that increments the swap file to 4GB and tested it on Ubuntu 16.04.

This can be run line by line or a bash script, but I use it to make headless installations.

#!/bin/bash
echo "====== Current Swap ======"
sudo swapon -s
echo "====== Turning Off Swap ======"
sudo swapoff /swapfile
echo "====== Allocating 4GB Swap ======"
sudo fallocate -l 4G /swapfile
echo "====== Making Swap ======"
sudo mkswap /swapfile
echo "====== Setting Permissions to Root Only  ======"
sudo chmod 600 /swapfile
echo "====== Turning On Swap ======"
sudo swapon /swapfile
echo "====== Current Swap ======"
sudo swapon -s
echo "====== Done! ======"
Denis Trofimov
  • 381
  • 3
  • 8
3

You might also want to check permissions. Other way to do this:

# check your swap
free

# turn off swap
sudo swapoff /swapfile

# To create the SWAP file, you will need to use this.
sudo fallocate -l 4G /swapfile  # same as "sudo dd if=/dev/zero of=/swapfile bs=1G count=4"

# Secure swap.
sudo chown root:root /swapfile
sudo chmod 0600 /swapfile

# Prepare the swap file by creating a Linux swap area.
sudo mkswap /swapfile

# Activate the swap file.
sudo swapon /swapfile

# Confirm that the swap partition exists.
sudo swapon -s

# check your swap again
free