说明:阿里云ECS默认镜像是没有SWAP分区的,在一些配置偏小的情况下需要SWAP分区来缓解小内存的尴尬
查看SWAP分区;显示没有此分区且大小为0。
[root@izuf6j9tjuw2zd5wodwiztz /]# swapon -s Filename Type Size Used Priority
[root@izuf6j9tjuw2zd5wodwiztz /]# free -h total used free shared buff/cache available Mem: 1.8G 57M 63M 340K 1.7G 1.6G Swap: 0B 0B 0B
配置SWAP分区
1、创建名为swapfile的块文件:
dd if=/dev/zero of=/swapfile bs=1024 count=4096k #创建出约4G左右的文件;修改count值可以控制文件大小
[root@izuf6j9tjuw2zd5wodwiztz /]# dd if=/dev/zero of=/swapfile bs=1024 count=4096k 4194304+0 records in 4194304+0 records out 4294967296 bytes (4.3 GB) copied, 37.7098 s, 114 MB/s
[root@izuf6j9tjuw2zd5wodwiztz /]# ll total 4194368 lrwxrwxrwx. 1 root root 7 Oct 15 2017 bin -> usr/bin dr-xr-xr-x. 5 root root 4096 Aug 20 13:21 boot drwxr-xr-x 19 root root 2960 Aug 20 13:55 dev drwxr-xr-x. 80 root root 4096 Aug 20 13:54 etc drwxr-xr-x. 2 root root 4096 Nov 5 2016 home lrwxrwxrwx. 1 root root 7 Oct 15 2017 lib -> usr/lib lrwxrwxrwx. 1 root root 9 Oct 15 2017 lib64 -> usr/lib64 drwx------. 2 root root 16384 Oct 15 2017 lost+found drwxr-xr-x. 2 root root 4096 Nov 5 2016 media drwxr-xr-x. 2 root root 4096 Nov 5 2016 mnt drwxr-xr-x. 2 root root 4096 Nov 5 2016 opt dr-xr-xr-x 73 root root 0 Aug 20 13:55 proc dr-xr-x---. 5 root root 4096 Aug 20 13:21 root drwxr-xr-x 21 root root 580 Aug 20 13:55 run lrwxrwxrwx. 1 root root 8 Oct 15 2017 sbin -> usr/sbin drwxr-xr-x. 2 root root 4096 Nov 5 2016 srv -rw-r--r-- 1 root root 4294967296 Aug 20 14:20 swapfile dr-xr-xr-x 13 root root 0 Aug 20 2018 sys drwxrwxrwt. 8 root root 4096 Aug 20 13:55 tmp drwxr-xr-x. 13 root root 4096 Oct 15 2017 usr drwxr-xr-x. 19 root root 4096 Oct 15 2017 var
2、转换块文件为SWAP分区:mkswap /swapfile
[root@izuf6j9tjuw2zd5wodwiztz /]# mkswap /swapfile Setting up swapspace version 1, size = 4194300 KiB no label, UUID=830e4908-f2ed-462e-b86a-52efcfda3dba
3、启用SWAP分区:swapon /swapfile
[root@izuf6j9tjuw2zd5wodwiztz /]# swapon /swapfile swapon: /swapfile: insecure permissions 0644, 0600 suggested.
4、根据提示配置SWAP文件权限:chmod -R 0600 /swapfile
[root@izuf6j9tjuw2zd5wodwiztz /]# chmod -R 0600 /swapfile
5、添加SWAP分区自动挂载信息至启动挂载配置文件/etc/fstab中
[root@izuf6j9tjuw2zd5wodwiztz /]# echo "/swapfile swap swap defaults 0 0" >> /etc/fstab
6、设置内存和SWAP分区使用比;添加使用比值至配置文件/etc/sysctl.conf中
[root@izuf6j9tjuw2zd5wodwiztz /]# echo "vm.swappiness = 60" >> /etc/sysctl.conf
7、重启系统后查询确认SWAP分区已经自动挂载并状态正常
[root@izuf6j9tjuw2zd5wodwiztz ~]# swapon -s Filename Type Size Used Priority /swapfile file 4194300 0 -1 [root@izuf6j9tjuw2zd5wodwiztz ~]# free -h total used free shared buff/cache available Mem: 1.8G 61M 1.5G 320K 199M 1.6G Swap: 4.0G 0B 4.0G