CentOS 7 添加Swap分区

匿名 (未验证) 提交于 2019-12-02 23:55:01

Swap分区,即交换分区,系统在运行内存不够时,与Swap进行交换。 其实,Swap的调整对Linux服务器,特别是Web服务器的性能至关重要。通过调整Swap,有时可以越过系统性能瓶颈,节省系统升级费用

设置Swap分区有两种方式

添加磁盘作为交换分区

如果你是用的是虚拟机,例如VMware ,那么为你的虚拟机添加一块1G或者2G的磁盘,swap分区一般设置为内存的2倍,在添加好磁盘以后,对磁盘进行分区,执行以下操作

获取添加磁盘的名字,一般第一块磁盘是/dev/sda,第二块磁盘是/dev/sdb

fdisk -l
Disk /dev/sdb: 2147 MB, 2147483648 bytes, 4194304 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

接下来是对磁盘操作,建立分区

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 0x2e4f401e.  #输入n,建立新分区 Command (m for help): n Partition type:    p   primary (0 primary, 0 extended, 4 free)    e   extended  #输入p,建立主分区,直接回车键即可 Select (default p): p  #选择分区号 Partition number (1-4, default 1): 1  #起始扇区,默认2048,直接回车 First sector (2048-4194303, default 2048):  Using default value 2048  #终止扇区,直接回车,默认所有未分配的扇区 Last sector, +sectors or +size{K,M,G} (2048-4194303, default 4194303):  Using default value 4194303 Partition 1 of type Linux and of size 2 GiB is set  #输入t,选择文件系统 Command (m for help): t Selected partition 1  #选择82,linux-swap格式,可输入L,查看所有代码 Hex code (type L to list all codes): 82 Changed type of partition 'Linux' to 'Linux swap / Solaris'  #输入w,对分区的操作进行保存 Command (m for help): w The partition table has been altered!  Calling ioctl() to re-read partition table. Syncing disks. 

再将sdb1设置为交换分区

mkswap /dev/sdb1
Setting up swapspace version 1, size = 2096124 KiB no label, UUID=7345dd38-c520-4fd6-97a4-d01e84146c06

确认下交换分区是否生效

free -m
              total        used        free      shared  buff/cache   available Mem:            972         182         519           7         270         600 Swap:          2047           0        2047 

使用文件作为交换分区

由于某些原因,我们无法增加磁盘,这时我们可以使用文件来作为交换分区

首先,我们通过命令来生成作为交换分区的文件

dd if=/dev/zero of=/root/swapfile bs=1M count=2048
2048+0 records in 2048+0 records out 2147483648 bytes (2.1 GB) copied, 23.1254 s, 92.9 MB/s

将创建的文件作为交换分区

mkswap /root/swapfile
Setting up swapspace version 1, size = 2097148 KiB no label, UUID=1dfb72f6-0ae6-4a56-a1ef-4417f1685ee5

启用交换分区

swapon /root/swapfile
swapon: /root/swapfile: insecure permissions 0644, 0600 suggested.

需要关闭交换分区时执行以下命令

swapoff /root/swapfile
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!