The Be Sure Blog

Code Snippets | Problem Solving | Tips & Tricks

The Be Sure Blog banner

How to increase the Swap Memory size in Ubuntu

posted on 21.5.2023 by Below Surface in "Ubuntu"

Let's increase the swap size from 512mb to 2gb without changing the partition permanently (this was too hot for me).

sudo swapon --show

Will display something like:

NAME     TYPE      SIZE USED PRIO     
/dev/sdb partition 512M 512M   -2

Let's increase the size from 512mb to 2gb:

sudo swapoff -a
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
sudo swapon --show

Result:

NAME      TYPE SIZE USED PRIO
/swapfile file   2G   0B   -2


After a reboot, you need to run:

sudo swapoff -a
sudo mkswap /swapfile
sudo swapon /swapfile


Or, let's create a script to run on startup, to set the swap to 2gb!

sudo nano startupscript.sh

Content:

#!/bin/bash
sudo swapoff -a
sudo mkswap /swapfile
sudo swapon /swapfile

Then save and close it and run:

sudo chmod +x startupscript.sh
readlink -f startupscript.sh

Copy the files link. Then run

sudo nano /etc/systemd/system/startupscript.service

Content:

[Unit]
Description=Startup Script
After=network.target

[Service] ExecStart=/yourlinkgoeshere/startupscript.sh

[Install] WantedBy=default.target

Then save and close it and run:

sudo systemctl enable startupscript.service
sudo systemctl start startupscript.service
sudo reboot

Test if the swap size is still 2gb after reboot:

htop


For troubleshooting the startupscript service:

sudo systemctl status startupscript.service

Tags:

ubuntu
swap memory

More posts of this category

How to delete an user in the Ubuntu terminal

Learn how to display all local users and how to delete them

Ubuntu

User permissons for folders and files in Ubuntu

Learn how to see which user has which rights and how to change them

Ubuntu