How do I increase the size of swapfile without removing it in the terminal?

126,610

Solution 1

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.

Solution 2

You should add a new swapfile instead of resizing the exist 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

Solution 3

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

Solution 4

(this answer completely rewritten since the downvote)

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.

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)
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:

# Make a backup copy of your /etc/fstab file just in case you
# make any mistakes
sudo cp /etc/fstab /etc/fstab.bak
# Add this swapfile entry to the end of the file to re-enable
# the swap file after each boot
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

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

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

Solution 5

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! ======"
Share:
126,610

Related videos on Youtube

Dave
Author by

Dave

Updated on September 18, 2022

Comments

  • Dave
    Dave almost 2 years

    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.

    • Boris Hamanov
      Boris Hamanov about 7 years
      How much RAM do you have? Is 2G enough? I think that you'll have to swapoff, create a new /swapfile, mkswap, and swapon -a
    • Ravexina
      Ravexina about 7 years
      Add a new swap file, follow the instruction of the above question. you can have 2 swap file ;)
    • Dave
      Dave about 7 years
      @Ravexina, A newbie question perhaps, but why would I want to add a new swap file rather than increasing the size of the existing one? Or is it not possible to increase an existing swap file?
    • Ravexina
      Ravexina about 7 years
      @Dave That's possible too, as you may know we can swapoff then dd and mkswap finally swapon. I thought you don't want to touch your file.
    • Dave
      Dave about 7 years
      @Ravexina, I don't want to destroy the swapfile. If what your suggesting destroys the swapfile but is the only way, I'm in.
    • Ravexina
      Ravexina about 7 years
      @Dave why you don't want to remove it ? is there any spacial reason?
    • tuxayo
      tuxayo almost 3 years
      «why you don't want to remove it» In my case it's to use hibernation. Because I have to put the resume_offset in my kernel params in grub.cfg which wound change if the file was recreated. Also hibernation can use only one swapfile so add another swapfile won't do it.
  • Boris Hamanov
    Boris Hamanov about 7 years
    sudo fallocate -l 2G /swapfile is probably safer than dd (although it doesn't keep the original swapfile), and it also needs a sudo chmod 600 /swapfile.
  • muru
    muru about 7 years
    @heynnema Doesn't fallocate make sparse files? The swapon manpage says sparse swap files are problematic (specifically mentioning fallocate).
  • Boris Hamanov
    Boris Hamanov about 7 years
    @muru I think the answer is yes, it creates sparse files, "as preallocation is done quickly by allocating blocks and marking them as uninitialized, requiring no IO to the data blocks"... but then the mkswap command should take care of that, no? The big concern with this dd example is if the user enters a space before the "swapfile", and wipes their root.
  • muru
    muru about 7 years
    @heynnema no, the mkswap manpage also says that the files should not contain any holes.
  • Boris Hamanov
    Boris Hamanov about 7 years
    @muru guess I'm wrong :-) Every time that I read how to create a /swapfile with the onset of 17.04 they used fallocate. I guess that we'll just have to use "disk destroyer"!
  • Boris Hamanov
    Boris Hamanov about 7 years
    Is the sudo chmod 600 /some/file required, or no?
  • Boris Hamanov
    Boris Hamanov about 7 years
    And does count=1K give a 1G file? count is in block size, yes? And that can be 512/4096? Or is my math wrong?
  • muru
    muru about 7 years
    @heynnema 1K*1M is 1G, so yes, it gives a 1G file. It can be whatever you want it to be. Once the swapfile is activated, you can't normally write to it or modify it (only root can, IIRC, so permissions wouldn't matter anyway).
  • joeytwiddle
    joeytwiddle about 7 years
    +1 This approach also makes it easy to disconnect one of the swapfiles if you later decide you need the disk space back.
  • David Foerster
    David Foerster about 7 years
    @heynnema: What you could do is to use fallocate to pre-allocate disk space and then use dd to fill the holes with zeros.
  • David Foerster
    David Foerster over 6 years
    @mgarey: Only you and the mods can delete your comments and I am neither you nor a mod.
  • Beshoy Girgis
    Beshoy Girgis about 6 years
    This really needs to be marked as the correct answer. Wow, bravo!
  • Christopher Rucinski
    Christopher Rucinski about 6 years
    Just as a note, I had to sudo all 5 lines
  • Christopher Rucinski
    Christopher Rucinski about 6 years
    @muru is this suppose to be a permanent solution? I performed these command on April 30th, but in sometime in the month of May, my second swapfile was gone. I didn't delete but it was gone
  • Ismael Miguel
    Ismael Miguel over 5 years
    Just did this in Linux Mint, with it running, and it went (slow to swapoff, but) smoothly. I've increased from 2GB to 9GB (8GB RAM + 1GB spare for whatever may be needed)
  • LnxSlck
    LnxSlck over 5 years
    You should have added an argument to the script, which is the amount of SWAP to be added and finally add it to fstab. But still, i like this
  • Charles Green
    Charles Green over 5 years
    Please note that fallocateshould bit be used to create the file, as it creates a sparce file. see man mkswap
  • borekon
    borekon over 5 years
    @CharlesGreen it worked me as i wrote, so it should work for almos anyone.
  • Charles Green
    Charles Green over 5 years
    I would sugegst reading man mkswap, especially the last pargraph before "Environment"
  • Admin
    Admin about 5 years
    worked on NanoPi Neo with Armbian v 5.65
  • Antony
    Antony about 5 years
    After reboot, in my Ubuntu 18.04, the system reverted to using the old swapfile instead of the new swapfile. I had to update /etc/fstab as mentioned by @borekon in his answer: echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab.
  • tuxayo
    tuxayo over 4 years
    «because it costs you nothing to do so» Except for hibernation. «The suspend image cannot span multiple swap partitions and/or swap files. It must fully fit in one swap partition or one swap file.[» wiki.archlinux.org/index.php/Power_management/…
  • tuxayo
    tuxayo over 4 years
    Actual source: «Q: Does swsusp (to disk) use only one swap partition or can it use multiple swap partitions (aggregate them into one logical space)? A: Only one swap partition, sorry.» kernel.org/doc/Documentation/power/swsusp.txt
  • muru
    muru over 4 years
    @tuxayo eh, Hibernation is iffy enough on Linux that I don't imagine it does cost nothing. In any case, it says " It must fully fit in one swap partition or one swap file", not that if there are multiple swap files it will refuse it fit into whichever one is large enough to accomodate it.
  • Gabriel Staples
    Gabriel Staples almost 4 years
    To the downvoter, I just massively rewrote this answer to make it expound upon and add new information to the knowledge-base already provided in the existing answers. I think it adds value now.
  • Moberg
    Moberg over 3 years
    Are there any restrictions on /some/file?
  • Dan Dascalescu
    Dan Dascalescu over 3 years
    Mint should really ask the user for the swap size on setup, especially when it creates a swap partition.
  • loop
    loop over 3 years
    Wouldn't cost a lot to add "swapoff /swapfile" as the first command because the question is about increasing the swapfile size.
  • Albin
    Albin about 3 years
    As of kernel 5.7 swap files created with fallocate will not always work, and dd is the recommended solution. Ex: "sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress". See man.archlinux.org/man/swapon.8#Files_with_holes
  • Albin
    Albin about 3 years
    As of kernel 5.7 swap files created with fallocate will not always work, and dd is the recommended solution. Ex: "sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress". See man.archlinux.org/man/swapon.8#Files_with_holes
  • Timo
    Timo almost 3 years
    I now have two swapfiles, one in /dev/sda2 and /swapfile. Which one will debian catch up for hibernate? With pm-hibernate I get Failed to hibernate system via logind: Access denied Failed to start hibernate.target: Unit hibernate.target is masked. Before the swapfile creation I got Failed to hibernate system via logind: Not enough swap space for hibernation
  • Gabriel Staples
    Gabriel Staples almost 3 years
    @Timo, any active swap file can be used, I believe. What does swapon --show show? Which of those two swap files is active? If both, the system can decide what to use and how, I assume, using both perhaps simultaneously even, as it sees fit.
  • Timo
    Timo almost 3 years
    great, I get /swapfile file 8G 36.3M -2 with swapon. But the error remain, access denied.
  • Gabriel Staples
    Gabriel Staples almost 3 years
    @Timo, try asking a new question on AskUbuntu. Paste a link here to your question so we can help if able.
  • Alex Rivas
    Alex Rivas almost 3 years
    This answer should be the best :). thks to you i did this very simple
  • tuxayo
    tuxayo almost 3 years
    @muru My message was too vague, if the need to have more swap space is to hibernate, then when adding another swapfile, then it must be setup as the hibernation one. Including getting the resume_offset and adding to kernel boot params, which is also needed when destroying and recreating. So when using hibernation it's likely the more convenient to resize instead of add a swapfile or recreate.
  • Gabriel Staples
    Gabriel Staples over 2 years
    @muru, great points about fallocate and the man pages. I've just cited you and added that information to my answer here. I was about to update my answer just now to use fallocate instead of dd, since it's supposed to be much faster, but then I realized my mistake as I scanned this page for fallocate and found your comments.
  • Admin
    Admin about 2 years
    Solid answer, clear and well documented.
  • Admin
    Admin about 2 years
    This answer obviously does not address the question at all.
  • Admin
    Admin about 2 years
    Answer removes swap, e.g. not what the OP asked.
  • Admin
    Admin about 2 years
    @DustWolf What you were looking for?
  • Admin
    Admin about 2 years
    @Ravexina see the OP question or title.
  • Admin
    Admin about 2 years
    @DustWolf The answer provides a solution to increase the swap file without removing it from the terminal. Exactly what the title is asking. What else should it supply so it can be considered the correct answer?
  • Admin
    Admin about 2 years
    @Ravexina swapoff removes the swap.
  • Admin
    Admin about 2 years
    @DustWolf You and OP have different definition of remove! they meant without removing the file! that's why they marked the question as the correct one. What you are asking for is a totally different question though I have touched it in my answer.