Add swap file linux

How to create a Linux swap file

Table of contents

Steps for creating a Linux swap file

  1. Display current swap space and RAM usage on Linux:
    $ free -h
    $ swapon —summary
  2. Next, create a new file that you will use for swap space either using the dd command:
    # Example: 2 Gib Linux swap file #
    $ sudo dd if=/dev/zero of= /swap-file count=2 bs=1GiB
  3. Make sure you set up correct Linux filesystem permissions for security reasons using the chmod command and chown command:
    $ sudo chmod -v 0600 /swap-file
    $ sudo chown -v root:root /swap-file
    # List permissions #
    $ ls -l /swap-file
  4. Run the following mkswap command to set up Linux swap area using a file:
    $ sudo mkswap /swap-file
  5. Activating a swap space by typing the swapon command:
    $ sudo swapon /swap-file

Adding swap file on Linux using the CLI

Displaying RAM and swap usage on Linux

You can use any one of the following commands:
$ swapon —summary
$ free -h
$ top
$ htop
$ vmstat

Display swap usage summary on Linux

How to activate swap space file persistently on Linux

Make sure our swap file is activated after the Linux system reboots. To make the change permanent, edit the /etc/fstab file:
$ sudo vi /etc/fstab
Append the following config directives:
/swap-file swap swap defaults 0 0
Save and close the file.

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

How to set up the swap space and file priority

By default, the Linux kernel uses the first activated swap space till it is full. Then kernel starts using the second swap space and so on. Nevertheless, Linux allows us to define priority. The default priority is -2, and Linux can use the highest priority first. Edit /etc/fstab and add the pri as follows:

Now my Linux kernel uses /swap-file-2 first with pri=10 . When that space is full, Linux usess the /swap-file with pri=5 . Finally, Linux uses /dev/sdb which has -2 priority.

A note about the swappiness

The swappiness value is defined in /proc/sys/vm/swappiness file. It controls how aggressively the Linux kernel will swap memory pages. Higher values increase aggressiveness, and lower values decrease aggressiveness. The default value is 60. Use the cat command to see values:
$ cat /proc/sys/vm/swappiness
60
I recommend leaving the default value, which works out great for most users. However, you can change it as follows to say 40:
$ sudo echo «vm.swappiness=10» | sudo tee -a /etc/sysctl.d/99-swappiness.conf
See “How to append text to a file when using sudo command on Linux or Unix” and “How to make changes to /proc/ filesystem permanently using sysctl.conf” for more information.

Removing swap file

Want to delete your swap file? Try:

  1. Disable the swap file:
    $ sudo swapoff -v /swap-file
  2. Remove the physical swap file using the rm command:
    $ sudo rm -v -i /swap-file
  3. Edit the /etc/fstab and remove entry for the swap file. For example:
    /swap-file swap swap defaults 0 0

Conclusion

You learned about creating a swap file on Linux to optimize VM/bare metal server or Linux desktop to increase available swap space. See the following man pages/documenation for more information by typing the man command:
$ man 8 mkswap
$ man 8 swapon
$ man 8 swapoff
$ man 8 mount
$ man 5 fstab

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

How To Create a Linux Swap File

In this article, we will explain swap space, and learn how to create swap space using a swap file in Linux: this is important in case we don’t have a swap partition created on the hard disk.

Swap space/partition is space on a disk created for use by the operating system when memory has been fully utilized. It can be used as virtual memory for the system; it can either be a partition or a file on a disk.

When the kernel runs out of memory, it can move idle/inactive processes into swap creating room for active processes in the working memory. This is memory management that involves swapping sections of memory to and from virtual memory.

With that said, below are the steps we can follow to create a swap space using a file.

How to Create and Enable Swap in Linux

1. In this example, we will create a swap file of size 2GB using the dd command as follows. Note that bs=1024 means read and write up to 1024 bytes at a time and count = (1024 x 2048)MB size of the file.

Alternatively, use the fallocate command as follows.

And then set the appropriate permissions on the file; make it readable only by root user as follows.

2. Now setup the file for swap space with the mkwap command.

3. Next, enable the swap file and add it to the system as a swap file.

4. Afterwards, enable the swap file to be mounted at boot time. Edit the /etc/fstab file and add the following line in it.

In the line above, each field means:

  • /mnt/swapfile – device/file name
  • swap – defines device mount point
  • swap – specifies the file-system type
  • defaults – describes the mount options
  • 0 – specifies the option to be used by the dump program
  • 0 – specifies the fsck command option

6. To set how often the swap file can be used by the kernel, open the /etc/sysctl.conf file and add the line below.

Note that the default value of how frequent swap space can be used is 60 (maximum value is 100). The higher the number, the more frequent swap space utilization by the kernel. When the value is set to 0, the swap file will only be used if the operating system has fully utilized memory.

6. Now verify the swap file was created using the swapon command.

Check Swap Space in Linux

We can optionally reboot the system to effect the above changes using the following command.

Remember to also read through these useful Linux memory management guides:

That’s It! If you have any issues, use the feedback form below to send us any questions or important additional ideas to this topic.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Ubuntu Linux Create and Add Swap File Tutorial

I ‘m a new Ubuntu Linux LTS user. I need additional swap space to improve my Ubuntu server performance. How can I add a swap space on Ubuntu Linux 14.04/16.04/18.04/20.04 LTS using command line over the ssh based session?

Tutorial requirements
Requirements Linux
Root privileges Yes
Difficulty Easy
Est. reading time 4 mintues
Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements Ubuntu Linux
Est. reading time 10m

Swap space is nothing but a disk storage used to increase the amount of memory available on the Ubuntu Linux server. In this tutorial, you will learn how to create and use a swap file on an Ubuntu Linux server.

What is a swap file on Ubuntu server or desktop system?

As a sysadmin it is necessary to add more swap space after installation on the server. Swap file allows Ubuntu Linux to use hard disk to increase virtual memory.

When the Ubuntu server runs low on memory, it swaps a section of RAM (say an idle program like foo) onto the hard disk (swap space) to free up memory for other programs. Then when you need that program (say foo again), kernel swapped out foo program, it changes places with another program in RAM.

Procedure to add a swap file on a Ubuntu Linux

Open the Terminal app or use the ssh client to get into the remote server. Login as a root user using sudo command:
sudo -s

Create a swap file command

Type the following command to create a 2GB swap file on Ubuntu:
# dd if=/dev/zero of=/swapfile bs=1G count=2
Sample outputs:

Verify that file has been created on the server:
# ls -lh /swapfile
Sample outputs:

Creating swap space using fallocate command instead of dd command

WARNING : Do not use the fallocate(1) command as it does not physically allocate the space, but swapon syscall requires a real space. The following example is for demo purposes and should be avoided at all costs.

Instead of the dd command, you can use the the faster fallocate command to create swap file as follows:
# fallocate -l 1G /swapfile-1
# ls -lh /swapfile-1
Sample outputs:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Secure the swap file

Type the following chmod command and chown command to secure and set correct file permission for security reasons:
# chown root:root /swapfile
# chmod 0600 /swapfile
# ls -lh /swapfile
Sample outputs:

A world-readable swap file is a huge local vulnerability. The above commands make sure only root user can read and write to the file.

Turn on the swap file

First, use the mkswap command as follows to enable the swap space on Ubuntu:
# mkswap /swapfile
Sample outputs:

Finally, activate the swap file, enter:
# swapon /swapfile

Verify new swap file and settings on Ubuntu

Type the following command
# swapon -s
Sample outputs:

You can also run the following commands to verify swap file and its usage:
# grep -i —color swap /proc/meminfo
# top
# htop
# atop

How can I disable swapfile on Ubuntu?

You need to use the swapoff command as follows:
# swapoff /swapfile
# swapon -s

Update /etc/fstab file

You need to make sure the swap file enabled when server comes on line after the reboot. Edit /etc/fstab file, enter:
# vi /etc/fstab
Append the following line:

Save and close the file.

Tuning the swap file i.e. tuning virtual memory

You can tune the following two settings:

  1. swappiness
  2. min_free_kbytes
  3. vfs_cache_pressure

How do I set swappiness on a Ubuntu server?

The syntax is:
# sysctl vm.swappiness=VALUE
# sysctl vm.swappiness=20
OR
# echo VALUE > /proc/sys/vm/swappiness
# echo 30 > /proc/sys/vm/swappiness

The value in /proc/sys/vm/swappiness file controls how aggressively the kernel will swap memory pages. Higher values increase agressiveness, lower values descrease aggressiveness. The default value is 60. To make changes permanent add the following line to /etc/sysctl.conf :

For database server such as Oracle or MySQL I suggest you set a swappiness value of 10. For more information see the official Linux kernel virtual memory settings page.

Conclusion

You learned how to add swap file under Ubuntu Linux. See the following resources:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Adding swap space is almost ALWAYS a bad idea. If your server is hitting swap, it means your applications are poorly configured. Either fix the app config, or add more RAM. There is no way that adding swap will increase performance – even a SSD hard drive is super slow compared to RAM.

But SOME swap may allow you time to kill a rogue program. It’s also much cheaper than buying RAM.

Nah ALWAYS a bad idea! Ass ram to your physical or virtual server! there’s no way adding swap is a good idea! swap is an idea of the last century where memory costed a lot! 😉

LOL sorry .. ADD ram to your physical… (sorry about that please moderator correct! thx ) 😉

Its good idea to solve our issue instantly but Adding physical RAM is permanent solutions.

1G RAM VPS get this error
dd: memory exhausted by input buffer of size 1073741824 bytes (1.0 GiB)
anyone can help?

dd if=/dev/zero of=/swapfile bs=1G count=4 creates a 4GB file – not 2GB like the tutorial states

@crossRT simply reduce the buffer size, like:
sudo dd if=/dev/zero of=/swapfile bs=500M count=4
Results in ->
-rw-r–r– 1 root root 2.0G Nov 27 23:31 /swapfile

yeah, i did it with fallocate command.
Anyway, thanks! =)

This is useful.
# dd if=/dev/zero of=/swapfile bs=1G count=4 did not worked.
but “# dd if=/dev/zero of=swapfile bs=M count=2000” worked instead of that.

more easy with this command :
root@sites:

# dd if=/dev/zero of=/swapfile bs=1M count=1024
root@sites:

# mkswap /swapfile
root@sites:

# nano /etc/fstab
than add this line :
/swapfile swap swap defaults 0 0

i added swap file but now showing in free command. is there any issue

Источник

Читайте также:  Как сменить пароль wifi windows 10
Оцените статью