Ubuntu20.02添加设置Swap内存交换分区

查看现有swap

1
free -h

输出结果:

1
2
3
4
5
$ free -h
total used free shared buff/cache available
Mem: 1.9Gi 910Mi 70Mi 37Mi 1.0Gi 879Mi
Swap: 947Mi 149Mi 798Mi

swap最好和内存一样(1~1.5倍).

查看原先swap文件位置

1
2
3
$ swapon -s  
Filename Type Size Used Priority
/swapfile file 969964 152780 -2

然后到swap文件夹目录

1
cd /

设置新交换内存

1
2
3
4
dd if=/dev/zero of=/swapmem bs=1G count=2
2+0 records in
2+0 records out
2147483648 bytes (2.1 GB, 2.0 GiB) copied, 21.0233 s, 102 MB/s

使用新内存

1
2
3
4
mkswap -f swapmem
mkswap: swapmem: insecure permissions 0644, 0600 suggested.
Setting up swapspace version 1, size = 2 GiB (2147479552 bytes)
no label, UUID=eca22c93-fd83-4bcb-89ab-3be10ff95f6f

设置权限

1
chmod 0600 swapmem

关闭原交换内存

1
swapoff /swapfile

查看内存使用率

1
2
3
4
$ free -h
total used free shared buff/cache available
Mem: 1.9Gi 1.1Gi 93Mi 47Mi 781Mi 672Mi
Swap: 0B 0B 0B

设置新交换内存

1
swapon /swapmem

查看内存使用率

1
2
3
4
$ free -h
total used free shared buff/cache available
Mem: 1.9Gi 1.1Gi 71Mi 47Mi 801Mi 671Mi
Swap: 2.0Gi 0B 2.0Gi

设置开机启动

1
2
3
4
vim /etc/fstab
UUID=fa207ef7-79a7-4092-8381-98c2a5143c74 / ext4 errors=remount-ro 0 1
10 /swapmem none swap sw 0 0
11 /dev/fd0 /media/floppy0 auto rw,user,noauto,exec,utf8 0 0

重启看看效果

1
2
3
4
5
free -h
$ free -h
total used free shared buff/cache available
Mem: 1.9Gi 791Mi 624Mi 41Mi 572Mi 1.0Gi
Swap: 2.0Gi 0B 2.0Gi

如果没有问题就删除原交换内存文件

1
rm /swapfile