Linux添加swap分区方法(以整块盘或分区作为虚拟内存)
建立一个普通的Linux分区(主分区、逻辑分区均可)
[root@devops-fleming /]# fdisk -l
Disk /dev/vda: 44.0 GB, 44023414784 bytes, 85983232 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x000b1b45
Device Boot Start End Blocks Id System
/dev/vda1 * 2048 85983198 42990575+ 83 Linux
Disk /dev/vdb: 85.9 GB, 85899345920 bytes, 167772160 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x990f0d05
Device Boot Start End Blocks Id System
/dev/vdb1 2048 83888127 41943040 83 Linux
/dev/vdb2 83888128 125831167 20971520 83 Linux
/dev/vdb3 125831168 167772159 20970496 83 Linux
以/dev/vdb3设为虚拟内存为例,可以看到分区的十六进制编码是83,即普通的Linux分区,而swap分区的编码是82。修改分区类型的十六进制编码,使用t命令改写分区十六进制编码
[root@devops-fleming /]# fdisk /dev/vdb
Welcome to fdisk (util-linux 2.23.2).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.
Command (m for help): t
Partition number (1-3, default 3): 3
Hex code (type L to list all codes): 82
Changed type of partition 'Linux' to 'Linux swap / Solaris'
Command (m for help): p
Disk /dev/vdb: 85.9 GB, 85899345920 bytes, 167772160 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x990f0d05
Device Boot Start End Blocks Id System
/dev/vdb1 2048 83888127 41943040 83 Linux
/dev/vdb2 83888128 125831167 20971520 83 Linux
/dev/vdb3 125831168 167772159 20970496 82 Linux swap / Solaris
Command (m for help): w
The partition table has been altered!
Calling ioctl() to re-read partition table.
Syncing disks.
可以看到/dev/vdb3的编码已经变成82 Linux swap / Solaris
格式化交换分区
[root@devops-fleming /]# mkswap /dev/vdb3
Setting up swapspace version 1, size = 20970492 KiB
no label, UUID=62976c8b-eeea-403c-914f-f6abfa735daf
启用交换分区
[root@devops-fleming /]# swapon /dev/vdb3
查看交换分区加载状态
[root@devops-fleming /]# free
total used free shared buff/cache available
Mem: 3880408 105288 2399132 500 1375988 3501300
Swap: 20970492 0 20970492
停用交换分区
[root@izj6c1me2wu2lepyg9fhg5z ~]# swapoff /dev/vdb3
不能直接使用mount命令挂载swap分区,因为swap分区是没有挂载点的。
系统启动时自动挂载,修改/etc/fstab配置文件
/dev/vdb3 swap swap defaults 0 0
查看交换分区
[root@devops-fleming /]# swapon -s
Filename Type Size Used Priority
/dev/vdb3 partition 20970492 0 -2