阿里云服务器添加swap分区
因为最近网站把内存使用的淋漓尽致,所以就想到了Linux下的swap。阿里云的ECS默认是不给开swap的,不过对于我这些穷屌丝来说,囊肿羞涩只能买512M的配置,所以不得不用到swap了。下面,大致记录了一下我添加swap分区的过程,供大家参考!

查看当前是没有swap的

[root@iZ23zvh0w6mZ lnmp1.1-full]# free -m
             total       used       free     shared    buffers     cached
Mem:           498        310        187          0         17        170
-/+ buffers/cache:        122        375
Swap:            0          0          0

[root@iZ23zvh0w6mZ lnmp1.1-full]# df -hT
Filesystem     Type   Size  Used Avail Use% Mounted on
/dev/xvda1     ext4    20G  3.7G   16G  20% /
tmpfs          tmpfs  250M     0  250M   0% /dev/shm

我们将swap挂载到/var下

[root@iZ23zvh0w6mZ lnmp1.1-full]# dd if=/dev/zero of=/var/swap bs=1M count=2048
2048+0 records in
2048+0 records out
2147483648 bytes (2.1 GB) copied, 47.8375 s, 44.9 MB/s

挂载完毕后,查看内存使用情况。发现swap出现了。

[root@iZ23zvh0w6mZ lnmp1.1-full]# free -m
             total       used       free     shared    buffers     cached
Mem:           498        456         41          0         10        100
-/+ buffers/cache:        346        152
Swap:         2047          0       2047

ok,swap已经可以使用了,接下来我们要将swap开机自动挂载。

编辑/etc/fstab文件

[root@iZ23zvh0w6mZ lnmp1.1-full]# vi /etc/fstab 
#
# /etc/fstab
# Created by anaconda on Mon Aug 11 16:27:41 2014
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
UUID=e76a7b8d-20c2-4f94-bdd1-f4054a34c206 / ext4 defaults,barrier=0 1 1
tmpfs                   /dev/shm                tmpfs   defaults        0 0
devpts                  /dev/pts                devpts  gid=5,mode=620  0 0
sysfs                   /sys                    sysfs   defaults        0 0
proc                    /proc                   proc    defaults        0 0
none                  /proc/xen               xenfs   defaults        0 0
/var/swap               swap                    swap    defaults        0 0

因为阿里云默认是不让用户使用swap的(貌似现在的系统模版更新了,这一行新装系统都没有了,如果没有请忽略此步。)。
编辑/etc/rc.d/rc.local文件,将文件中的swapoff行注释或删掉。

[root@iZ23zvh0w6mZ lnmp1.1-full]# vi /etc/rc.d/rc.local 
#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.

touch /var/lock/subsys/local
ulimit -SHn 65535
#swapoff -a //加上"#"号注释掉或者直接删除

完成之后reboot查看

Welcome to aliyun Elastic Compute Service!

[root@iZ23zvh0w6mZ ~]# free -m
             total       used       free     shared    buffers     cached
Mem:           498        106        391          0         10         47
-/+ buffers/cache:         48        449
Swap:         2047          0       2047