Linux/Swap Space

From Dev Wiki
< Linux(Redirected from Linux Swap Space)
Jump to navigation Jump to search

Swap space is a section of hard drive space that is allocated specifically to be used as a memory (RAM) overflow.
Swap memory isn't as fast as standard memory. So if having memory issues, the proper solution is to buy more memory. The next best solution is to create/increase swap space.
By default, linux will not allocate any hard drive space as swap space. It must be done manually.

Viewing Available Swap Space

To specifically view swap space only, run the command:

  • swapon --show

If this command returns no output, then there is no swap space allocated.

Alternatively, to view all allocated memory (including swap space), run the command:

  • free -h


Allocating Swap Space

Before allocating swap space, make sure you have enough hard drive space for what you want to allocate. See Linux Hard Drive Management for details.

Note: If you want to adjust already existing swap space, then first use swapoff -a to disable all existing swap space.

Create swap space with the command:

  • sudo fallocate -l <size_to_allocate> /swapfile
    • <size_to_allocate> should be 1G to allocate 1 gig, 2G to allocate 2 gigs, etc.


Make sure to set it to be only root-accessible with:

  • sudo chmod 600 /swapfile


Finally, flag this as swap space with:

  • sudo mkswap /swapfile


Activating Swap Space for Use

To test that the swap works, we can temporarily enable it with:

  • swapon /swapfile

Note that this command will only work until you restart the system. But you can now use a command to view available swap space, to verify that it allocated correctly.

If the swap space allocated correctly, we can now make it permanent by editing /etc/fstab and adding the line:

  • /swapfile swap swap defaults 0 0


Adjusting the Swappiness Property

Swappiness defines how often the system attempts to swap data out of RAM and into the swap space. This value ranges between 0-100, and read in by the system as a percentage.

  • Closer to 0 means that the system will swap to disk less often, unless necessary.
  • Closer to 100 means that the system will attempt to swap more often.

Using swap space is expensive compared to normal memory, so you probably want this value to be low in cases where performance is important (such as server applications).

You can view the current swappiness value with the below commands. The default is likely around 60.

  • Older Location (May not exist on newer systems):
    • cat /proc/sys/vm/swappiness
  • Newer Location (May not exist on older systems):
    • cat /sys/fs/cgroup/memory/memory.swappiness


To change current swappiness, edit /etc/sysctl.conf and add the line:

  • vm.swappiness=<swap_value>, where <swap_value> is the swap value you desire.
    • Ex: vm.swappiness=10