Monday, October 5, 2009

linux: adding swap space on-the-fly to your system

You might find that the swap partition you specified at install-time just isn't enough anymore. Maybe you've added more RAM to your machine and need to increase the swap partition accordingly. Or maybe you're upgrading your system to a version that uses more swap in relation to physical RAM. Perhaps you're running Oracle. In case your machine is swapping like mad and you just can't take it down right now to add more RAM, you can add more swap space on the fly using the following procedure. As an example, to keep the machine from running out of memory entirely and freezing up, we'll add 128 MB more swap space by creating a swap file. First we check out the memory usage:

[root@domain /root]# free -m
total used free shared buffers cached
Mem: 251 242 8 22 11 32
-/+ buffers/cache: 198 52
Swap: 133 133 0

Make sure we have 128 MB laying around somewhere:

[root@domain /root]# df
Filesystem 1k-blocks Used Available Use% Mounted on
/dev/hda9 132207 33429 91952 27% /
/dev/hda1 15522 2537 12184 17% /boot
/dev/hda6 6143236 739000 5092176 13% /opt
/dev/hda7 1035660 836204 146848 85% /usr
/dev/hda5 2071384 344048 1622112 17% /usr/local
/dev/hda8 303344 14439 273244 5% /var

OK, we're going to make a swap file in /opt by using dd to create a file 128 MB in size.

[root@domain /opt]# dd if=/dev/zero of=swapfile bs=1024 count=132207
132207+0 records in
132207+0 records out
[root@domain /opt]# ls -l
total 132364
drwxr-xr-x 20 usr-3 users 4096 May 22 10:46 usr-3
drwxr-xr-x 2 root root 16384 Feb 21 07:04 lost+found
-rw-r--r-- 1 root root 135379968 May 29 11:52 swapfile

Let's not make it world-readable...

[root@domain /opt]# chmod 600 swapfile
[root@domain /opt]# ls -l
total 132364
drwxr-xr-x 20 usr-3 users 4096 May 22 10:46 usr-3
drwxr-xr-x 2 root root 16384 Feb 21 07:04 lost+found
-rw------- 1 root root 135379968 May 29 11:52 swapfile

Now we set up the swap area and enable it.

[root@domain /opt]# mkswap swapfile
Setting up swapspace version 1, size = 135372800 bytes
[root@domain /opt]# swapon swapfile

And voila! Twice as much swap as before.

[root@domain /opt]# free
total used free shared buffers cached
Mem: 257632 254632 3000 2512 36172 15096
-/+ buffers/cache: 203364 54268
Swap: 268708 136512 132196

You can append a line like this to /etc/fstab to enable your swap file automatically at boot time:

/opt/swapfile swap swap defaults 0 0


source

No comments: