1
+ How to Create and Enable a Swap File in Linux
2
+
3
+ 1. In this example, we will create a swap file of size 2GB using the dd command as follows.
4
+ 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.
5
+
6
+ logon as root
7
+
8
+ # dd if=/dev/zero of=/mnt/swapfile bs=1024 count=2097152
9
+
10
+ Alternatively, use the fallocate command as follows.
11
+
12
+ # fallocate --length 2GiB /mnt/swapfile
13
+
14
+ And then set the appropriate permissions on the file; make it readable only by root user as follows.
15
+
16
+ # chmod 600 /mnt/swapfile
17
+
18
+ 2. Now setup the file for swap space with the mkswap command.
19
+
20
+ # mkswap /mnt/swapfile
21
+
22
+ 3. Next, enable the swap file and add it to the system as a swap file.
23
+
24
+ # swapon /mnt/swapfile
25
+
26
+ 4. Afterwards, enable the swap file to be mounted at boot time.
27
+ Edit the /etc/fstab file and add the following line in it.
28
+
29
+ /mnt/swapfile swap swap defaults 0 0
30
+
31
+ In the line above, each field means:
32
+
33
+ /mnt/swapfile – device/file name
34
+ swap – defines device mount point
35
+ swap – specifies the file-system type
36
+ defaults – describes the mount options
37
+ 0 – specifies the option to be used by the dump program
38
+ 0 – specifies the fsck command option
39
+
40
+ 6. To set how often the swap file can be used by the kernel,
41
+ open the /etc/sysctl.conf file and add the line below.
42
+
43
+ vm.swappiness=10
44
+
45
+ Note that the default value of how frequent swap space can be used is 60 (maximum value is 100).
46
+ The higher the number, the more frequent swap space utilization by the kernel.
47
+ When the value is set to 0, the swap file will only be used if the operating system has fully utilized memory.
48
+
49
+ 6. Now verify the swap file was created using the swapon command.
50
+
51
+ # swapon -s
52
+
53
+ # Your new swap file will be active after each reboot.
0 commit comments