Display current swap space and RAM usage on Linux: $ free -h $ swapon —summary
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
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
Run the following mkswap command to set up Linux swap area using a file: $ sudo mkswap /swap-file
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:
Disable the swap file: $ sudo swapoff -v /swap-file
Remove the physical swap file using the rm command: $ sudo rm -v -i /swap-file
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
Источник
Linux creating swap file
This page provides an introduction to swap space and paging on GNU/Linux. It covers creation and activation of swap partitions and swap files.
Linux divides its physical RAM (random access memory) into chunks of memory called pages. Swapping is the process whereby a page of memory is copied to the preconfigured space on the hard disk, called swap space, to free up that page of memory. The combined sizes of the physical memory and the swap space is the amount of virtual memory available.
Support for swap is provided by the Linux kernel and user-space utilities from the util-linux package.
Contents
Swap space
Swap space can take the form of a disk partition or a file. Users may create a swap space during installation or at any later time as desired. Swap space can be used for two purposes, to extend the virtual memory beyond the installed physical memory (RAM), and also for suspend-to-disk support.
If it is beneficial to extend the virtual memory with swap depends on the amount of installed physical memory. If the amount of physical memory is less than the amount of memory required to run all the desired programs, then it may be beneficial to enable swap. This avoids out of memory conditions, where the Linux kernel OOM killer mechanism will automatically attempt to free up memory by killing processes. To increase the amount of virtual memory to the required amount, add the necessary difference (or more) as swap space.
The biggest drawback of enabling swap is its lower performance, see section #Performance. Hence, enabling swap is a matter of personal preference: some prefer programs to be killed over enabling swap and others prefer enabling swap and slower system when the physical memory is exhausted.
To check swap status, use:
Or to show physical memory as well as swap usage:
Swap partition
The factual accuracy of this article or section is disputed.
A swap partition can be created with most GNU/Linux partitioning tools. Swap partitions are typically designated as type 82 . Even though it is possible to use any partition type as swap, it is recommended to use type 82 in most cases since systemd will automatically detect it and mount it (see below).
To set up a partition as Linux swap area, the mkswap(8) command is used. For example:
To enable the device for paging:
To enable this swap partition on boot, add an entry to /etc/fstab :
where the device_UUID is the UUID of the swap space.
See fstab for the file syntax.
Activation by systemd
systemd activates swap partitions based on two different mechanisms. Both are executables in /usr/lib/systemd/system-generators . The generators are run on start-up and create native systemd units for mounts. The first, systemd-fstab-generator , reads the fstab to generate units, including a unit for swap. The second, systemd-gpt-auto-generator inspects the root disk to generate units. It operates on GPT disks only, and can identify swap partitions by their type GUID, see systemd#GPT partition automounting for more information.
Disabling swap
To deactivate specific swap space:
Alternatively use the -a switch to deactivate all swap space.
Since swap is managed by systemd, it will be activated again on the next system startup. To disable the automatic activation of detected swap space permanently, run systemctl —type swap to find the responsible .swap unit and mask it.
Swap file
As an alternative to creating an entire partition, a swap file offers the ability to vary its size on-the-fly, and is more easily removed altogether. This may be especially desirable if disk space is at a premium (e.g. a modestly-sized SSD).
Manually
Swap file creation
Use dd to create a swap file the size of your choosing. For example, creating a 512 MiB swap file:
Set the right permissions (a world-readable swap file is a huge local vulnerability):
After creating the correctly sized file, format it to swap:
Activate the swap file:
Finally, edit the fstab configuration to add an entry for the swap file:
For additional information, see fstab#Usage.
Remove swap file
To remove a swap file, it must be turned off first and then can be removed:
Finally remove the relevant entry from /etc/fstab .
Automated
zram-generator
The aim of this tool is the creation of zram devices. It is written in Rust and resides in systemd’s GitHub. It can be installed with the zram-generator package. Configuration is straightforward and explained in the README.
systemd-swap
systemd-swap is a script for creating hybrid swap space from zram swaps, swap files and swap partitions. It is not affiliated with the systemd project.
Install the systemd-swap package. Uncomment and set swapfc_enabled=1 in the Swap File Chunked section of /etc/systemd/swap.conf . Start/enable the systemd-swap service.
Visit the authors GitHub page for more information and setting up the recommended configuration.
Swap encryption
Performance
Swap operations are usually significantly slower than directly accessing data in RAM. Disabling swap entirely to improve performance can sometimes lead to a degradation, since it decreases the memory available for VFS caches, causing more frequent and costly disk I/O.
Swap values can be adjusted to help performance:
Swappiness
The swappiness sysctl parameter represents the kernel’s preference (or avoidance) of swap space. Swappiness can have a value between 0 and 200 (max 100 if Linux /sys/fs/cgroup/memory/memory.swappiness or /proc/sys/vm/swappiness can be read in order to obtain the raw integer value.
To temporarily set the swappiness value:
To set the swappiness value permanently, create a sysctl.d(5) configuration file. For example:
To test and more on why this may work, take a look at this article.
VFS cache pressure
Another sysctl parameter that affects swap performance is vm.vfs_cache_pressure , which controls the tendency of the kernel to reclaim the memory which is used for caching of VFS caches, versus pagecache and swap. Increasing this value increases the rate at which VFS caches are reclaimed[1]. For more information, see the Linux kernel documentation.
Priority
If you have more than one swap file or swap partition you should consider assigning a priority value (0 to 32767) for each swap area. The system will use swap areas of higher priority before using swap areas of lower priority. For example, if you have a faster disk ( /dev/sda ) and a slower disk ( /dev/sdb ), assign a higher priority to the swap area located on the fastest device. Priorities can be assigned in fstab via the pri parameter:
Or via the —priority parameter of swapon:
If two or more areas have the same priority, and it is the highest priority available, pages are allocated on a round-robin basis between them.
Using zswap or zram
Zswap is a Linux kernel feature providing a compressed write-back cache for swapped pages. This increases the performance and decreases the IO-Operations. ZRAM creates a virtual compressed Swap-file in memory as alternative to a swapfile on disk.
Striping
There is no necessity to use RAID for swap performance reasons. The kernel itself can stripe swapping on several devices, if you just give them the same priority in the /etc/fstab file. Refer to The Software-RAID HOWTO for details.
Источник
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.