centos服务器的内存不够?用虚拟内存扩展内存

背景

个人vps主机,物理内存小,虚拟内存0,理论上讲虚拟内存应该要有物理内存的2倍大小。
导致yum安装的软件的时候报错 [Errno 5] [Errno 12] 无法分配内存

设置虚拟内存

  1. 打开终端,切换到root用户,输入:free -m查看内存状态
    1
    2
    3
    4
    5
    [maker@LLM ~]$ free -m
    total used free shared buff/cache available
    Mem: 992 189 79 13 722 614
    Swap: 0 0 0
    Swap也就是虚拟内存为0
  1. 选择一个较大的分区,建立分区文件
    1
    2
    3
    4
    [root@LLM ~]# dd if=/dev/zero of=/opt/swap bs=1024 count=1024000
    1024000+0 records in
    1024000+0 records out
    1048576000 bytes (1.0 GB) copied, 16.6877 s, 62.8 MB/s

该命令表示在opt分区建立名为swap,大小为1G的虚拟内存文件

  1. 将swap文件设置为swap分区文件

    1
    2
    3
    4
    chmod 600 /opt/swap    //注意更改swap文件的权限
    [root@LLM ~]# mkswap /opt/swap
    Setting up swapspace version 1, size = 1023996 KiB
    no label, UUID=fc47f29e-31af-401e-856d-0fec5262179e
  2. 激活swap,启用分区交换文件

    1
    swapon /opt/swap
  3. 现在看下结果

    1
    2
    3
    4
    [root@LLM ~]# free -m
    total used free shared buff/cache available
    Mem: 992 191 63 13 737 625
    Swap: 999 0 999

卸载虚拟内存

  1. 首先停止swap分区

    1
    2
    3
    4
    5
    [root@LLM ~]# swapoff /opt/swap
    [root@LLM ~]# free -m
    total used free shared buff/cache available
    Mem: 992 191 63 13 738 626
    Swap: 0 0 0
  2. 其次删除掉swap文件即可
    首先看一下磁盘大小

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    [root@LLM ~]# df -h
    Filesystem Size Used Avail Use% Mounted on
    /dev/vda1 40G 3.9G 34G 11% /
    devtmpfs 487M 0 487M 0% /dev
    tmpfs 497M 4.0K 497M 1% /dev/shm
    tmpfs 497M 420K 496M 1% /run
    tmpfs 497M 0 497M 0% /sys/fs/cgroup
    tmpfs 100M 0 100M 0% /run/user/0
    tmpfs 100M 0 100M 0% /run/user/1001
    [root@LLM ~]# rm -rf /opt/swap
    [root@LLM ~]# df -h
    Filesystem Size Used Avail Use% Mounted on
    /dev/vda1 40G 3.0G 35G 8% /
    devtmpfs 487M 0 487M 0% /dev
    tmpfs 497M 4.0K 497M 1% /dev/shm
    tmpfs 497M 420K 496M 1% /run
    tmpfs 497M 0 497M 0% /sys/fs/cgroup
    tmpfs 100M 0 100M 0% /run/user/0
    tmpfs 100M 0 100M 0% /run/user/1001

可以看出删除后多了1G的空间