Thursday, April 22, 2010

creating a swap file on the fly

I dislike setting up swap partitions; I really do.  Instead, with super fast servers with coolio I/O, 
I create swap files on the fly.  As follows is an example of a fresh install and the steps taken.

root@newsystem:/# free -m
             total       used       free     shared    buffers     cached
Mem:          4048       3902        145          0          7       3798
-/+ buffers/cache:         96       3951
Swap:            0          0          0

Let's add 8G.

root@newsystem:/# dd if=/dev/zero of=swap bs=1024 count=8388608

Turn the file into a swap file.

root@newsystem:/# mkswap /swap

Turn on swap.

root@newsystem:/# swapon /swap

Add swap to system when system starts; via the following line:
/swap           swap            swap    defaults        0       0

root@newsystem:/# vi /etc/fstab 

Check it out.

root@newsystem:/# free -m
             total       used       free     shared    buffers     cached
Mem:          4048       3900        147          0          5       3784
-/+ buffers/cache:        110       3937
Swap:         8191          0       8191

Neat.

...

Recommended size of a linux swap file:

1G RAM .... 2G swap
2G RAM .... 4G swap
4G RAM .... 8G swap
8G RAM .... 12G swap
16G RAM .... 24G swap
32G RAM .... 32G swap
...


To create a swap file, use the "dd" command to create an empty file.
Next you need to use mkswap command to set up a Linux swap area on a device or in a file

1. Login as root

2. Create and determine the size of the new swap file in Megabytes and multiply by 1024 to 
determine the number of blocks.  Do this via "dd". 
For example, the block size of a 1GB swap file is (1024 * 1024MB = 1048576 block size). Type 
following command to create 1GB swap file:

# dd if=/dev/zero of=/swap bs=1024 count=1048576

Note: "swap" is the name of your swapfile.

3. Setup the swap file with the command: mkswap. Type the following to setup your swap file:

# mkswap /swap

4. To enable the swap file immediately but not automatically at boot time. Type:

# swapon /swap

5. To enable the new swap file automatically at the boot, you need to edit the file /etc/fstab and add the following line.

/swap swap swap defaults 0 0

The swap file will be enabled at each time the system boots.

6. You can verify the swap file is working fine with these commands:

# cat /proc/swaps
- or -
# free

a solaris interlude
/usr/sbin/mkfile 5g /path/to/swapfile
/usr/bin/swap -a /path/to/swapfile
/usr/bin/swap -l
Next, edit /etc/vfstab.. e.g.:
/swap    -       -   swap    -       no     -

No comments: