Linux下swap(交换分区)的增删改

swap介绍
Linux 的交换分区(swap),或者叫内存置换空间(swap space),是磁盘上的一块区域,可以是一个分区,也可以是一个文件,或者是他们的组合。交换分区的作用是,当系统物理内存吃紧时,Linux 会将内存中不常访问的数据保存到swap 上,这样系统就有更多的物理内存为各个进程服务,而当系统需要访问 swap 上存储的内容时,再将 swap 上的数据加载到内存中,也就是说,当正常内存已经占满,不够用时,系统就会使用虚拟内存,以缓解服务器压力,避免崩溃,增强稳定性。但是其速度有限,常只是作为突发情况的缓冲。
【Linux下swap(交换分区)的增删改】使用 swap 交换分区,显著的优点是,通过操作系统的调度,应用程序实际可以使用的内存空间将远远超过系统的物理内存。由于硬盘空间的价格远比 RAM 要低,因此这种方式无疑是经济实惠的。当然,频繁地读写硬盘,会显著降低操作系统的运行速率,这也是使用 swap 交换分区最大的限制。

使用 swap 必须要知道它存在的缺点,以便判断何时使用交换分区。使用交换分区的好处当然就是可以一定程度的缓解内存空间紧张的问题。然而,由于 CPU 所读取的数据都来自于内存,交换分区则是存放在磁盘上的,磁盘的速度和内存比较起来慢了好几个数量级,如果不停的读写 swap,那么对系统的性能肯定有影响,尤其是当系统内存很吃紧的时候,读写 swap 空间发生的频率会很高,导致系统运行很慢。

如果使用是桌面系统,由于系统会自动将不常用的内存数据移到 swap 上,对桌面程序来说,有可能会导致最小化一个程序后,再打开时小卡一下,因为需要将 swap 上的数据重新加载到内存中来。在部署了数据库的系统上,也不建议用交换分区,因为频繁地在内存和磁盘上相互导数据会影响数据库性能。

很多时候我们安装系统的时候并没有考虑到,并不会划分swap分区,而当需要用到时,可以通过命令手动增加,删除,修改swap虚拟内存。下面就详细记录介绍一下如何操作虚拟内存。
新增swap有两种方式:

  • 磁盘上新增一个分区(lvm分区或直接分区),用分区作为swap。
  • 磁盘上新增一个固定大小的文件,用文件作为swap。
推荐: 使用分区方式,新增一个分区。分区类型fdisk下为82,gdisk下为8200,partep分区标记没有定义swap,其实分区后不更改分区类型也行测试也可以用,但为了在分区工具下方便查看最好还是把分区类型改成swap对应的分区类型,本人理解分区类型就是分区软件下用来描述分区所要承载的文件系统的类型,比如分区类型为83表示为linxu分区,用于格式化成ext3 ext4等linux文件系统,分区创建的方法这里就不写了前面有分区创建的方法。
准备环境
[root@localhost ~]# cat /etc/redhat-release CentOS Linux release 7.5.1804 (Core) [root@localhost ~]# uname -r 3.10.0-862.el7.x86_64 [root@localhost ~]# free -m totalusedfreesharedbuff/cacheavailable Mem:39341213474113383545 Swap:000 [root@localhost ~]# df -Th FilesystemTypeSizeUsed Avail Use% Mounted on /dev/sda2xfs19G1.1G18G6% / devtmpfsdevtmpfs2.0G02.0G0% /dev tmpfstmpfs2.0G02.0G0% /dev/shm tmpfstmpfs2.0G12M2.0G1% /run tmpfstmpfs2.0G02.0G0% /sys/fs/cgroup /dev/sda1xfs297M107M191M36% /boot tmpfstmpfs394M0394M0% /run/user/0 [root@localhost ~]# blkid /dev/sda1: UUID="0705b568-de2f-40dc-940f-ea2c91b3f059" TYPE="xfs" /dev/sda2: UUID="57859f61-6df4-40dc-8da5-6998dc7df3a7" TYPE="xfs" /dev/sr0: UUID="2018-05-03-21-07-04-00" LABEL="CentOS 7 x86_64" TYPE="iso9660" PTTYPE="dos" [root@localhost ~]# ls -l /dev/sd[a-z] brw-rw----. 1 root disk 8, 0 Feb 25 10:26 /dev/sda

新增swap分区操作
VMware Workstation添加一块硬盘
  • 在"我的计算机"中选择该主机--右键--设置--添加--硬盘--下一步--下一步--下一步--完成 添加硬盘步骤。
Linux下swap(交换分区)的增删改
文章图片

  • 命令:echo "- - -" > /sys/class/scsi_host/host0/scan
  • 1.新增添磁盘,还不能直接显示出来,要想出现要对磁盘进行扫描(实际生产环境中不需要,都是热插拔技术):
  • 2.假如 fdisk -l 还是未发现新硬盘,则将上面命令中的host0,替换为host1,host2,....看看;
  • 3.我们再查看系统日志/var/log/messages,发现对SCSI设备进行了一次重新扫描,用fdisk -l也看到了新增加的磁盘了。
查看新增的硬盘 [root@localhost ~]# echo "- - -" > /sys/class/scsi_host/host0/scan [root@localhost ~]# ls -l /dev/sd[a-z] brw-rw----. 1 root disk 8,0 Feb 25 10:26 /dev/sda brw-rw----. 1 root disk 8, 16 Feb 25 10:51 /dev/sdb[root@localhost ~]# fdisk -lDisk /dev/sda: 21.5 GB, 21474836480 bytes, 41943040 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: 0x00094eb7Device BootStartEndBlocksIdSystem /dev/sda1*204861644730720083Linux /dev/sda2616448404623351992294483LinuxDisk /dev/sdb: 21.5 GB, 21474836480 bytes, 41943040 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

方式一:在/dev/sdb磁盘上使用lvm2创建分区 (lvm分区参考前文:Linux下使用lvm管理)
安装lvm2 [root@localhost ~]# yum install lvm2 -y [root@localhost ~]# rpm -qa |grep lvm2 lvm2-libs-2.02.187-6.el7_9.5.x86_64 lvm2-2.02.187-6.el7_9.5.x86_64

方式二:在/dev/sdb磁盘上直接创建物理分区
[root@localhost ~]# fdisk /dev/sdb 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.Device does not contain a recognized partition table Building a new DOS disklabel with disk identifier 0x3d895f28.Command (m for help): n//创建分区 Partition type: pprimary (0 primary, 0 extended, 4 free) eextended Select (default p)://回车,默认p为主分区,e为扩展分区 Using default response p Partition number (1-4, default 1)://回车,默认分区号 First sector (2048-41943039, default 2048)://回车(默认) Using default value 2048 Last sector, +sectors or +size{K,M,G} (2048-41943039, default 41943039): +8G//新增分区大小 Partition 1 of type Linux and of size 8 GiB is setCommand (m for help): m//显示相关命令 Command action atoggle a bootable flag bedit bsd disklabel ctoggle the dos compatibility flag ddelete a partition gcreate a new empty GPT partition table Gcreate an IRIX (SGI) partition table llist known partition types mprint this menu nadd a new partition ocreate a new empty DOS partition table pprint the partition table qquit without saving changes screate a new empty Sun disklabel tchange a partition's system id uchange display/entry units vverify the partition table wwrite table to disk and exit xextra functionality (experts only)Command (m for help): p//显示信息Disk /dev/sdb: 21.5 GB, 21474836480 bytes, 41943040 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: 0x3d895f28Device BootStartEndBlocksIdSystem /dev/sdb1204816779263838860883LinuxCommand (m for help): l//列出所有类型 0Empty24NEC DOS81Minix / old Lin bfSolaris 1FAT1227Hidden NTFS Win 82Linux swap / So c1DRDOS/sec (FAT- 2XENIX root39Plan 983Linuxc4DRDOS/sec (FAT- 3XENIX usr3cPartitionMagic84OS/2 hidden C:c6DRDOS/sec (FAT- 4FAT16 <32M40Venix 8028685Linux extendedc7Syrinx 5Extended41PPC PReP Boot86NTFS volume set daNon-FS data 6FAT1642SFS87NTFS volume set dbCP/M / CTOS / . 7HPFS/NTFS/exFAT 4dQNX4.x88Linux plaintext deDell Utility 8AIX4eQNX4.x 2nd part 8eLinux LVMdfBootIt 9AIX bootable4fQNX4.x 3rd part 93Amoebae1DOS access aOS/2 Boot Manag 50OnTrack DM94Amoeba BBTe3DOS R/O bW95 FAT3251OnTrack DM6 Aux 9fBSD/OSe4SpeedStor cW95 FAT32 (LBA) 52CP/Ma0IBM Thinkpad hi ebBeOS fs eW95 FAT16 (LBA) 53OnTrack DM6 Aux a5FreeBSDeeGPT fW95 Ext'd (LBA) 54OnTrackDM6a6OpenBSDefEFI (FAT-12/16/ 10OPUS55EZ-Drivea7NeXTSTEPf0Linux/PA-RISC b 11Hidden FAT1256Golden Bowa8Darwin UFSf1SpeedStor 12Compaq diagnost 5cPriam Ediska9NetBSDf4SpeedStor 14Hidden FAT16 <3 61SpeedStorabDarwin bootf2DOS secondary 16Hidden FAT1663GNU HURD or Sys afHFS / HFS+fbVMware VMFS 17Hidden HPFS/NTF 64Novell Netwareb7BSDI fsfcVMware VMKCORE 18AST SmartSleep65Novell Netwareb8BSDI swapfdLinux raid auto 1bHidden W95 FAT3 70DiskSecure Mult bbBoot Wizard hid feLANstep 1cHidden W95 FAT3 75PC/IXbeSolaris bootffBBT 1eHidden W95 FAT1 80Old MinixCommand (m for help): t//修改类型 Selected partition 1 Hex code (type L to list all codes): 82//修改为Linux swap类型 Changed type of partition 'Linux' to 'Linux swap / Solaris'Command (m for help): p//再次显示,确认修改成功Disk /dev/sdb: 21.5 GB, 21474836480 bytes, 41943040 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: 0x3d895f28Device BootStartEndBlocksIdSystem /dev/sdb1204816779263838860882Linux swap / SolarisCommand (m for help): w//保存退出 The partition table has been altered!Calling ioctl() to re-read partition table. Syncing disks.[root@localhost ~]# fdisk -lDisk /dev/sda: 21.5 GB, 21474836480 bytes, 41943040 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: 0x00094eb7Device BootStartEndBlocksIdSystem /dev/sda1*204861644730720083Linux /dev/sda2616448404623351992294483LinuxDisk /dev/sdb: 21.5 GB, 21474836480 bytes, 41943040 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: 0x3d895f28Device BootStartEndBlocksIdSystem /dev/sdb1204816779263838860882Linux swap / Solaris格式化swap分区 [root@localhost ~]# mkswap /dev/sdb1 Setting up swapspace version 1, size = 8388604 KiB no label, UUID=ebe6d07e-a3df-4c08-af8f-8129b0989c72[root@localhost ~]# free -m totalusedfreesharedbuff/cacheavailable Mem:39341223460113513543 Swap:000开启swap分区 [root@localhost ~]# swapon /dev/sdb1[root@localhost ~]# free -m totalusedfreesharedbuff/cacheavailable Mem:39341273454113513537 Swap:819108191[root@localhost ~]# blkid /dev/sda1: UUID="0705b568-de2f-40dc-940f-ea2c91b3f059" TYPE="xfs" /dev/sda2: UUID="57859f61-6df4-40dc-8da5-6998dc7df3a7" TYPE="xfs" /dev/sr0: UUID="2018-05-03-21-07-04-00" LABEL="CentOS 7 x86_64" TYPE="iso9660" PTTYPE="dos" /dev/sdb1: UUID="ebe6d07e-a3df-4c08-af8f-8129b0989c72" TYPE="swap将新添加的交换分区添加到/etc/fstab文件中使之开机启动 [root@localhost ~]# echo "UUID=ebe6d07e-a3df-4c08-af8f-8129b0989c72swapswapdefaults00" >> /etc/fstab到此就完成了直接用物理分区新增为swap

删除swap分区操作
关闭swap [root@localhost ~]# swapoff /dev/sdb1注释掉或删除/etc/fstab中的分区信息 [root@localhost ~]# sed -i_bak 's/^[^#].*swap*/#&/g' /etc/fstab [root@localhost ~]# sed -i_bak '/swap/d' /etc/fstab[root@localhost ~]# fdisk /dev/sdb 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.Device does not contain a recognized partition table Building a new DOS disklabel with disk identifier 0x8737f2c3.Command (m for help): m Command action atoggle a bootable flag bedit bsd disklabel ctoggle the dos compatibility flag ddelete a partition gcreate a new empty GPT partition table Gcreate an IRIX (SGI) partition table llist known partition types mprint this menu nadd a new partition ocreate a new empty DOS partition table pprint the partition table qquit without saving changes screate a new empty Sun disklabel tchange a partition's system id uchange display/entry units vverify the partition table wwrite table to disk and exit xextra functionality (experts only)Command (m for help): d No partition is defined yet!Command (m for help): pDisk /dev/sdb1: 8589 MB, 8589934592 bytes, 16777216 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: 0x8737f2c3Device BootStartEndBlocksIdSystemCommand (m for help): w The partition table has been altered!Calling ioctl() to re-read partition table.WARNING: Re-reading the partition table failed with error 22: Invalid argument. The kernel still uses the old table. The new table will be used at the next reboot or after you run partprobe(8) or kpartx(8) Syncing disks.[root@localhost ~]# free -m totalusedfreesharedbuff/cacheavailable Mem:39341013695111373620 Swap:000到此就完全删除了swap分区

新增swap交换文件操作
使用dd命令创建名为swapfile的swap交换文件,文件路径为/swapfile,bs为单位,count为大小(8G) [root@localhost ~]# dd if=/dev/zero of=/swapfile bs=1MB count=8192 8192+0 records in 8192+0 records out 8192000000 bytes (8.2 GB) copied, 55.0475 s, 149 MB/s[root@localhost ~]# df -Th FilesystemTypeSizeUsed Avail Use% Mounted on /dev/sda2xfs19G8.6G11G46% / devtmpfsdevtmpfs2.0G02.0G0% /dev tmpfstmpfs2.0G02.0G0% /dev/shm tmpfstmpfs2.0G12M2.0G1% /run tmpfstmpfs2.0G02.0G0% /sys/fs/cgroup /dev/sda1xfs297M107M191M36% /boot tmpfstmpfs394M0394M0% /run/user/0[root@localhost ~]# blkid /dev/sda1: UUID="0705b568-de2f-40dc-940f-ea2c91b3f059" TYPE="xfs" /dev/sda2: UUID="57859f61-6df4-40dc-8da5-6998dc7df3a7" TYPE="xfs" /dev/sr0: UUID="2018-05-03-21-07-04-00" LABEL="CentOS 7 x86_64" TYPE="iso9660" PTTYPE="dos" 验证交换文件大小 [root@localhost ~]# du -sh /swapfile 7.7G /swapfile修改文件的权限,避免其他用户对这个文件进行误操作 [root@localhost ~]# ls -l /swapfile -rw-r--r--. 1 root root 8192000000 Mar 24 14:27 /swapfile [root@localhost ~]# chmod 600 /swapfile [root@localhost ~]# ls -l /swapfile -rw-------. 1 root root 8192000000 Mar 24 14:27 /swapfile将交换文件格式化并转换为swap分区 [root@localhost ~]# mkswap /swapfile Setting up swapspace version 1, size = 7999996 KiB no label, UUID=42e38c74-4067-499a-bee4-e53542262f91[root@localhost ~]# free -m totalusedfreesharedbuff/cacheavailable Mem:39341021271137043515 Swap:000挂载并激活分区 [root@localhost ~]# swapon /swapfile [root@localhost ~]# free -m totalusedfreesharedbuff/cacheavailable Mem:39341081201137043508 Swap:781207812设置开机自动挂载该分区 [root@localhost ~]# echo "/swapfile swap swap defaults 0 0" >> /etc/fstab重新生成挂载单元/etc/fstab [root@localhost ~]# systemctl daemon-reload

删除swap交换文件操作
查看swap [root@localhost ~]# cat /proc/swaps FilenameTypeSize Used Priority /swapfilefile7999996 0 -1[root@localhost ~]# free -m totalusedfreesharedbuff/cacheavailable Mem:39341103687111363612 Swap:781207812禁用交换文件 [root@localhost ~]# swapoff -v /swapfile swapoff /swapfile重新生成挂载单元/etc/fstab [root@localhost ~]# systemctl daemon-reload删除实际文件 [root@localhost ~]# rm /swapfile -rf注释掉或删除/etc/fstab中的分区信息 [root@localhost ~]# sed -i_bak 's/^[^#].*swap*/#&/g' /etc/fstab [root@localhost ~]# sed -i_bak '/swap/d' /etc/fstab再次检查swap [root@localhost ~]# free -m totalusedfreesharedbuff/cacheavailable Mem:39341043693111363618 Swap:000[root@localhost ~]# cat /proc/swaps FilenameTypeSize Used Priority

附:在lvm2上使用swap【官方文档】

    推荐阅读