跳到主要内容

创建swap内存空间

创建swap内存空间

云上购买的cvm机器一般都没有开启swap空间, 稍微npm build编译就会导致内存不够, 整个机器 oom 丢失响应, 开始强制删任务, 虽然并不会重启.

参考文档

Linux内存拓展(内存不足SWAP解决方案)

https://www.cnblogs.com/Axianba/p/13131620.html

执行实录

  • 创建swap文件
ubuntu@VM-0-4-ubuntu:~$ sudo dd if=/dev/zero of=/swapfile bs=1024 count=4096000
4096000+0 records in
4096000+0 records out
4194304000 bytes (4.2 GB, 3.9 GiB) copied, 14.3766 s, 292 MB/s

ubuntu@VM-0-4-ubuntu:~$ ls -alh /
total 4.0G
drwxr-xr-x 22 root root 4.0K Oct 13 2022 lib
-rw-r--r-- 1 root root 4.0G Jun 13 23:31 swapfile
dr-xr-xr-x 13 root root 0 May 30 19:24 sys
drwxrwxrwt 14 root root 4.0K Jun 13 23:30 tmp
drwxr-xr-x 13 root root 4.0K May 30 21:10 usr
  • 加载swap
ubuntu@VM-0-4-ubuntu:~$ sudo mkswap /swapfile
mkswap: /swapfile: insecure permissions 0644, 0600 suggested.
Setting up swapspace version 1, size = 3.9 GiB (4194299904 bytes)
no label, UUID=2e16c959-2695-4e71-a069-a45969f2e9a4

ubuntu@VM-0-4-ubuntu:~$ sudo swapon /swapfile
swapon: /swapfile: insecure permissions 0644, 0600 suggested.

ubuntu@VM-0-4-ubuntu:~$ swapon -s
Filename Type Size Used Priority
/swapfile file 4095996 0 -2
ubuntu@VM-0-4-ubuntu:~$ htop

```bash
free -h
total used free shared buff/cache available
Mem: 3.4G 1.7G 252M 19M 1.5G 1.5G
Swap: 3.9G 577M 3.3G
  • 持久化开机启动
ubuntu@VM-0-4-ubuntu:~$ sudo vim /etc/fstab

ubuntu@VM-0-4-ubuntu:~$ cat /etc/fstab
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point> <type> <options> <dump> <pass>
UUID=5ba34c3d-bd14-451d-a7d8-09a64009e3f1 / ext4 errors=remount-ro 0 1
/swapfile swap swap defaults 0 0
ubuntu@VM-0-4-ubuntu:~$ sudo mount -a

ubuntu@VM-0-4-ubuntu:~$ sudo mount -fav
/ : ignored
swap : ignored
ubuntu@VM-0-4-ubuntu:~$ sudo findmnt --verify --verbose
/
[ ] target exists
[ ] FS options: errors=remount-ro
[ ] UUID=5ba34c3d-bd14-451d-a7d8-09a64009e3f1 translated to /dev/vda1
[ ] source /dev/vda1 exists
[ ] FS type is ext4
swap
[W] non-bind mount source /swapfile is a directory or regular file
[ ] FS type is swap

0 parse errors, 0 errors, 1 warning

chatgpt 解释

dd 命令

picture 1

mkswapswapon命令

picture 2

mount命令

picture 3