扩展Vagrant虚拟机系统磁盘和根文件系统

文章目录

    • 1. VBox镜像导入
    • 2. Vagrantfile示例和虚拟机创建
    • 3. 修改系统磁盘大小
    • 4. 扩充根文件系统:

本文不会介绍如何在你的系统上安装VirtualBox和Vagrant软件,实际上安装他们是很简单的事情,只需要阅读官方文档来安装即可。

总之,安装了VirtualBox和Vagrant软件之后,只需要下载并导入特定的操作系统的VBox镜像,就可以使用Vagrant来快速在VirtualBox中创建所需的虚拟机环境,Vagrant程序会根据我们的要求来自动设置虚拟机(如主机名、IP地址以及安装软件等,甚至是运行你的Shell脚本。),大大节省了我们手动创建和安装虚拟机系统的时间。

但是,这样创建的虚拟机其默认系统磁盘容量是根据镜像而定的,一般不会太大。例如,本文用于创建虚拟机的VBox镜像为CentOS-7-x86_64-Vagrant-1812_01.VirtualBox.box,其创建的虚拟机系统磁盘大小仅为40GB(系统的根文件系统(/)为40GB)。

本文将讲解如何使用上述VBox镜像来创建虚拟机,并修改系统磁盘大小和扩充根文件系统。

CentOS的VBox镜像可以在http://cloud.centos.org/centos/下载。

1. VBox镜像导入

首先下载所需镜像,然后执行如下命令将其导入:

[root@orcltest ~]# vagrant box add centos7/1812_01 ./CentOS-7-x86_64-Vagrant-1812_01.VirtualBox.box

查看导入的VBox:

[root@orcltest ~]# vagrant box list
centos7/1812_01 (virtualbox, 0)

2. Vagrantfile示例和虚拟机创建

本文参照如下操作步骤来创建虚拟机:

  1. 创建一个Vagrangfile存放目录(建议以虚拟机名称来命名方便管理):

    [root@orcltest ~]# cd && mkdir -p vagrantdata/orcltest
    
  2. 在该目录下创建一个名为Vagrantfile的文件

    [root@orcltest ~]# cd ~/vagrantdata/orcltest
    [root@orcltest ~]# touch Vagrantfile
    
  3. 并编辑文件内容如下:

    Vagrant.configure("2") do |config|
      config.vm.hostname = "orcltest"        # 指定虚拟机主机名
      config.vm.box = "centos7/1812_01"        # 指定使用的VBox名
      config.vm.box_check_update = false
      config.vm.network "private_network", ip: "10.128.0.41"        # 指定虚拟机IP地址
      config.vm.network :forwarded_port, guest: 22, host: 10041, auto_correct: true   # 将虚拟机的22端口于宿主机的端口进行捆绑便于外部ssh连接
      config.vm.provider "virtualbox" do |vb|
        vb.name = "vagrant_orcltest"        # 指定该虚拟机在VirtualBox虚拟机清单中的名称
        vb.gui = false
        vb.memory = "12800"        # 指定虚拟机内存大小
        vb.cpus = 4        # 指定虚拟机CPU数量
      end
      config.vm.provision "shell", inline: <<-SHELL        # 指定虚拟机启动后要执行的脚本或命令:
        yum install -y openssh-server net-tools wget dstat &> /dev/null
        echo 'LoginGraceTime 0' >> /etc/ssh/sshd_config
        echo 'PermitRootLogin yes' >> /etc/ssh/sshd_config
        echo 'PasswordAuthentication yes' >> /etc/ssh/sshd_config
        sed -i "/^PasswordAuthentication no/d" /etc/ssh/sshd_config
        echo r00tr00t |passwd --stdin root        # 设置root用户密码
        systemctl enable sshd
        systemctl restart sshd
        echo "export TZ='Asia/Shanghai'" >> /etc/profile
        echo "export LANG=en_US.UTF-8" >> /etc/profile
        echo "alias df='df -hTP'" >> /etc/profile
        echo "alias df='df -hP'" >> /etc/profile
        echo "alias free='free -h'" >> /etc/profile
        sed -i "/orcltest/d" /etc/hosts        # 虚拟机首次启动会将设置的主机名映射为127.0.0.1,并记录与/etc/hosts文件下(建议删除该行)
        sed -i "/SELINUX=/s/enforcing/disabled/g" /etc/selinux/config
        echo >> /etc/hosts
        echo "10.128.0.41    orcltest" >> /etc/hosts
      SHELL
    end
    

    上面文件中,我们指定了root用户的密码并启用sshd服务来允许外部SSH连接。同时,Vagrant在启动虚拟机后会默认创建一个名为vagrant的普通用户,其密码也为vagrant。上面定义了虚拟机的IP地址(config.vm.network "private_network", ip: "10.128.0.41"),该配置将在宿主机创建一个虚拟网络,然后虚拟机启动后将使用该指定的IP地址桥接到该专有网络中。同时Vagrant会自动为虚拟机创建一个私有网络(10.0.2.15/24),虚拟机可以通过NAT协议连接到外部网络/互联网中。

  4. 在Vagrantfile所在目录下执行如下命令启动虚拟机:

    [root@oratest orcltest]# vagrant up
    Bringing machine 'default' up with 'virtualbox' provider...
    ==> default: Importing base box 'centos7/1812_01'...
    ==> default: Matching MAC address for NAT networking...
    ==> default: Setting the name of the VM: vagrant_orcltest
    ==> default: Fixed port collision for 22 => 2222. Now on port 2202.
    ==> default: Vagrant has detected a configuration issue which exposes a
    ==> default: vulnerability with the installed version of VirtualBox. The
    ==> default: current guest is configured to use an E1000 NIC type for a
    ==> default: network adapter which is vulnerable in this version of VirtualBox.
    ==> default: Ensure the guest is trusted to use this configuration or update
    ==> default: the NIC type using one of the methods below:
    ==> default:
    ==> default:   https://www.vagrantup.com/docs/virtualbox/configuration.html#default-nic-type
    ==> default:   https://www.vagrantup.com/docs/virtualbox/networking.html#virtualbox-nic-type
    ==> default: Clearing any previously set network interfaces...
    ==> default: Preparing network interfaces based on configuration...
        default: Adapter 1: nat
        default: Adapter 2: hostonly
    ==> default: Forwarding ports...
        default: 22 (guest) => 10041 (host) (adapter 1)
        default: 22 (guest) => 2202 (host) (adapter 1)        #动态绑定到宿主机的SSH端口可能并不固定。
    ==> default: Running 'pre-boot' VM customizations...
    ==> default: Booting VM...
    ==> default: Waiting for machine to boot. This may take a few minutes...
        default: SSH address: 127.0.0.1:2202
        default: SSH username: vagrant
        default: SSH auth method: private key
        default:
        default: Vagrant insecure key detected. Vagrant will automatically replace
        default: this with a newly generated keypair for better security.
        default:
        default: Inserting generated public key within guest...
        default: Removing insecure key from the guest if it's present...
        default: Key inserted! Disconnecting and reconnecting using new SSH key...
    ==> default: Machine booted and ready!
    ==> default: Checking for guest additions in VM...
        default: No guest additions were detected on the base box for this VM! Guest
        default: additions are required for forwarded ports, shared folders, host only
        default: networking, and more. If SSH fails on this machine, please install
        default: the guest additions and repackage the box to continue.
        default:
        default: This is not an error message; everything may continue to work properly,
        default: in which case you may ignore this message.
    ==> default: Setting hostname...
    ==> default: Configuring and enabling network interfaces...
    ==> default: Rsyncing folder: /root/vagrantdata/orcltest/ => /vagrant
    ==> default: Running provisioner: shell...
        default: Running: inline script
        default: Changing password for user root.
        default: passwd: all authentication tokens updated successfully.
        
    [root@oratest orcltest]# VBoxManage list vms
    "vagrant_orcltest" {b1821a49-0ab1-4b9e-ac85-8ea3b668360e}
    
    [root@oratest orcltest]# ps -ef |grep VBox |grep orcltest
    root      9634 22384  4 13:43 ?        00:00:36 /usr/lib/virtualbox/VBoxHeadless --comment vagrant_orcltest --startvm b1821a49-0ab1-4b9e-ac85-8ea3b668360e --vrde config
    
    [root@oratest orcltest]# ss -tunlp |grep 10041
    tcp    LISTEN     0      10      *:10041        *:*        users:(("VBoxHeadless",pid=9634,fd=21))
    
  5. 继续在Vagrantfile所在目录下执行如下命令连接虚拟机,并验证结果:

    [root@oratest orcltest]# vagrant ssh
    Last login: Fri May 31 05:49:25 2019 from 10.0.2.2
    
    [vagrant@orcltest ~]$ su - root
    Password:
    [root@orcltest ~]# df -hTP
    Filesystem     Type      Size  Used Avail Use% Mounted on
    /dev/sda1      xfs        40G  2.9G   38G   8% /
    devtmpfs       devtmpfs  6.1G     0  6.1G   0% /dev
    tmpfs          tmpfs     6.1G     0  6.1G   0% /dev/shm
    tmpfs          tmpfs     6.1G  8.5M  6.1G   1% /run
    tmpfs          tmpfs     6.1G     0  6.1G   0% /sys/fs/cgroup
    tmpfs          tmpfs     1.3G     0  1.3G   0% /run/user/1000
    
    [root@orcltest ~]# fdisk -l
    
    Disk /dev/sda: 42.9 GB, 42949672960 bytes, 83886080 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: 0x0009cf06
    
       Device Boot      Start         End      Blocks   Id  System
    /dev/sda1   *        2048    83886079    41942016   83  Linux
    
    [root@orcltest ~]# ifconfig eth1
    eth1: flags=4163  mtu 1500
            inet 10.128.0.41  netmask 255.255.255.0  broadcast 10.128.0.255
            inet6 fe80::a00:27ff:feb2:9ad7  prefixlen 64  scopeid 0x20
            ether 08:00:27:b2:9a:d7  txqueuelen 1000  (Ethernet)
            RX packets 3  bytes 1770 (1.7 KiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 24  bytes 2746 (2.6 KiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
    

你也可以使用ssh命令(ssh [email protected])连接到该虚拟机。

3. 修改系统磁盘大小

需要说明的是,本文讲解的是如何加大系统磁盘的大小并修改系统的根文件系统容量。理论上,系统磁盘加大以后,你也可以新建磁盘分区(主分区或者逻辑分区均可,如/dev/sda2等)并在新分区上创建文件系统并单独挂载到独立挂载点(如/data),这并不在本文讨论范围内。因此,简单的说本文讲解如何将上述虚拟机的根文件系统(/)从40GB扩展到80GB。

另外,你也可以参考相关VirtualBox虚拟机的管理资料,来为虚拟机新增额外的数据磁盘(如/dev/sdb),并在该磁盘创建新的分区或使用LVM机制管理的文件系统,这也不在本文讨论范围内。实际上在VirtualBox的UI界面上就可以进行操作。

默认情况下,Vagrant在VirtualBox内创建虚拟机其磁盘格式为VMDK。因此我们可以利用工具将VMDK镜像转换为可扩展的VDI(虚拟磁盘镜像)镜像,依次达到扩展虚拟机磁盘的目的。最后,将其重新挂载到虚拟上。虚拟机启动后,利用系统管理命令,如fdiskresize2fs(ext*格式)或xfs_growfs(xfs格式)命令来实现根目录的扩展。

  1. 关闭上面创建的虚拟机(orcltest):

    [root@oratest ~]# cd ~/vagrantdata/orcltest/
    [root@oratest orcltest]# vagrant halt
    ==> default: Attempting graceful shutdown of VM...
    
  2. 从该虚拟机的虚拟磁盘镜像(VMDK格式),克隆一个新的虚拟磁盘镜像,格式设置为VDI:

    [root@oratest vagrant_orcltest]# ls -l
    total 975104
    -rw------- 1 root root 1003618304 May 31 14:02 centos-7-1-1.x86_64.vmdk
    drwx------ 2 root root         22 May 31 13:43 Logs
    -rw------- 1 root root       2234 May 31 14:02 vagrant_orcltest.vbox
    -rw------- 1 root root       2234 May 31 13:43 vagrant_orcltest.vbox-prev
    
    [root@oratest vagrant_orcltest]# VBoxManage clonehd "centos-7-1-1.x86_64.vmdk" "centos-7-1-1.x86_64.vdi" --format vdi
    0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
    
    Clone medium created in format 'vdi'. UUID: d08f5150-530f-4b66-8984-e8ad66ea8b71
    [root@oratest vagrant_orcltest]# ls -lh centos-7-1-1.x86_64.v*
    -rw------- 1 root root 963M May 31 14:10 centos-7-1-1.x86_64.vdi
    -rw------- 1 root root 958M May 31 14:02 centos-7-1-1.x86_64.vmdk
    

    注意:虚拟机文件存放在VirtualBox的虚拟机存放目录,如我的环境为Linux上的VirtualBox,其路径为:/root/VirtualBox VMs。上面的文件大小为文件占用空间,并不代表镜像的实际大小。

  3. 扩展克隆的VDI镜像,本例中,我们将其扩展到80GB:

    [root@oratest vagrant_orcltest]# VBoxManage modifyhd "centos-7-1-1.x86_64.vdi" --resize 81920
    0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
    
    [root@oratest vagrant_orcltest]# ls -lh centos-7-1-1.x86_64.v*
    -rw------- 1 root root 963M May 31 14:10 centos-7-1-1.x86_64.vdi
    -rw------- 1 root root 958M May 31 14:02 centos-7-1-1.x86_64.vmdk
    
    [root@oratest vagrant_orcltest]# VBoxManage showhdinfo centos-7-1-1.x86_64.vdi
    UUID:           d08f5150-530f-4b66-8984-e8ad66ea8b71
    Parent UUID:    base
    State:          locked write
    Type:           normal (base)
    Location:       /root/VirtualBox VMs/vagrant_orcltest/centos-7-1-1.x86_64.vdi
    Storage format: vdi
    Format variant: dynamic default
    Capacity:       40960 MBytes
    Size on disk:   963 MBytes
    Encryption:     disabled
    In use by VMs:  vagrant_orcltest (UUID: b1821a49-0ab1-4b9e-ac85-8ea3b668360e)
    
  4. 将克隆出来的VDI磁盘连接到虚拟机上:

    查看一下当前虚拟机配置文件:

    [root@oratest vagrant_orcltest]# cat vagrant_orcltest.vbox |grep -E '(HardDisk |StorageController )'
            
          
    

    将克隆的磁盘连接到虚拟机上,并检查结果:

    [root@oratest vagrant_orcltest]# VBoxManage storageattach vagrant_orcltest --storagectl "IDE" --port 0 --device 0 --type hdd --medium centos-7-1-1.x86_64.vdi
    
    [root@oratest vagrant_orcltest]# cat vagrant_orcltest.vbox |grep 'HardDisk '
            
            
    
  5. 启动虚拟机:

    [root@oratest vagrant_orcltest]# cd ~/vagrantdata/orcltest/
    [root@oratest orcltest]# vagrant up
    Bringing machine 'default' up with 'virtualbox' provider...
    ==> default: Clearing any previously set forwarded ports...
    ==> default: Fixed port collision for 22 => 2222. Now on port 2202.
    ==> default: Vagrant has detected a configuration issue which exposes a
    ==> default: vulnerability with the installed version of VirtualBox. The
    ==> default: current guest is configured to use an E1000 NIC type for a
    ==> default: network adapter which is vulnerable in this version of VirtualBox.
    ==> default: Ensure the guest is trusted to use this configuration or update
    ==> default: the NIC type using one of the methods below:
    ==> default:
    ==> default:   https://www.vagrantup.com/docs/virtualbox/configuration.html#default-nic-type
    ==> default:   https://www.vagrantup.com/docs/virtualbox/networking.html#virtualbox-nic-type
    ==> default: Clearing any previously set network interfaces...
    ==> default: Preparing network interfaces based on configuration...
        default: Adapter 1: nat
        default: Adapter 2: hostonly
    ......
    ......
    
  6. 登陆虚拟机,检查结果:

    [root@oratest orcltest]# vagrant ssh
    Last login: Fri May 31 05:50:17 2019 from 10.0.2.2
    [vagrant@orcltest ~]$ su - root
    Password:
    Last login: Fri May 31 13:50:24 CST 2019 on pts/0
    [root@orcltest ~]# fdisk -l
    
    Disk /dev/sda: 85.9 GB, 85899345920 bytes, 167772160 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: 0x0009cf06
    
       Device Boot      Start         End      Blocks   Id  System
    /dev/sda1   *        2048    83886079    41942016   83  Linux
    

    可以看到,磁盘已经加大。

4. 扩充根文件系统:

我们使用的镜像并没有使用LVM技术来对磁盘进行分区和封装。因此,不能使用LVM的相关技术和命令(如vgextendlvextend等)来扩展磁盘分区。

因此,本文参考了How can I resize an ext root partition at runtime?一文的方法来扩展根分区(/dev/sda1)。

  1. 修改磁盘分区表,以扩展磁盘分区大小:

    [root@orcltest ~]# fdisk /dev/sda
    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.
    
    
    Command (m for help): d        # 删掉分区1的信息(/dev/sda1)
    Selected partition 1
    Partition 1 is deleted
    
    Command (m for help): p        # 查看磁盘分区情况
    
    Disk /dev/sda: 85.9 GB, 85899345920 bytes, 167772160 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: 0x0009cf06
    
       Device Boot      Start         End      Blocks   Id  System
    
    Command (m for help): n        # 新建分区
    Partition type:
       p   primary (0 primary, 0 extended, 4 free)
       e   extended
    Select (default p): p        # 选择主分区类型
    Partition number (1-4, default 1): 1    # 编号设置为1(一定要设置为1(保持于/dev/sda1一致))
    First sector (2048-167772159, default 2048):    # 起始柱面(默认最小)
    Using default value 2048
    Last sector, +sectors or +size{K,M,G} (2048-167772159, default 167772159):    # 结束柱面(默认最大)
    Using default value 167772159
    Partition 1 of type Linux and of size 80 GiB is set
    
    Command (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 16: Device or resource busy.
    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@orcltest ~]# fdisk -l /dev/sda
    
    Disk /dev/sda: 85.9 GB, 85899345920 bytes, 167772160 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: 0x0009cf06
    
       Device Boot      Start         End      Blocks   Id  System
    /dev/sda1            2048   167772159    83885056   83  Linux        # 结束柱面信息已经被修改
    

    注意:上面适用fdisk命令中删掉sda1分区的信息后,请一定不要马上执行w命令保存分区信息。这样可以保持分区的起始柱面不变的情况下,将分区的结束柱面往后进行调整。这样保存后相当于仅仅修改了sda1分区的结束柱面信息。

  2. 退出虚拟机,并重启虚拟机:

    [root@orcltest ~]# exit
    logout
    [vagrant@orcltest ~]$ exit
    logout
    Connection to 127.0.0.1 closed.
    [root@oratest orcltest]# vagrant reload
    ==> default: Attempting graceful shutdown of VM...
    ==> default: Clearing any previously set forwarded ports...
    ==> default: Fixed port collision for 22 => 2222. Now on port 2202.
    ==> default: Vagrant has detected a configuration issue which exposes a
    ==> default: vulnerability with the installed version of VirtualBox. The
    ==> default: current guest is configured to use an E1000 NIC type for a
    ==> default: network adapter which is vulnerable in this version of VirtualBox.
    ==> default: Ensure the guest is trusted to use this configuration or update
    ==> default: the NIC type using one of the methods below:
    ......
    ......
    
  3. 重新登陆虚拟机,并扩展根文件系统:

    [root@oratest orcltest]# vagrant ssh
    Last login: Fri May 31 06:22:10 2019 from 10.0.2.2
    [vagrant@orcltest ~]$ su - root
    Password:
    Last login: Fri May 31 14:22:14 CST 2019 on pts/0
    [root@orcltest ~]# df -hTP /
    Filesystem     Type  Size  Used Avail Use% Mounted on
    /dev/sda1      xfs    40G  2.9G   38G   8% /
    
    [root@orcltest ~]# which xfs_growfs
    /sbin/xfs_growfs
    
    [root@orcltest ~]# xfs_growfs /dev/sda1
    meta-data=/dev/sda1              isize=512    agcount=4, agsize=2621376 blks
             =                       sectsz=512   attr=2, projid32bit=1
             =                       crc=1        finobt=0 spinodes=0
    data     =                       bsize=4096   blocks=10485504, imaxpct=25
             =                       sunit=0      swidth=0 blks
    naming   =version 2              bsize=4096   ascii-ci=0 ftype=1
    log      =internal               bsize=4096   blocks=5119, version=2
             =                       sectsz=512   sunit=0 blks, lazy-count=1
    realtime =none                   extsz=4096   blocks=0, rtextents=0
    data blocks changed from 10485504 to 20971264
    
    [root@orcltest ~]# df -hTP /
    Filesystem     Type  Size  Used Avail Use% Mounted on
    /dev/sda1      xfs    80G  2.9G   78G   4% /
    

    可以看到根文件系统已经扩展到80GB。

    如果你使用的镜像为EL 6系列,那么根文件系统格式可能为Ext4,需要使用resize2fs /dev/sda1来扩展根文件系统。

你可能感兴趣的:(Vagrant,VirtualBox,Linux,VirtualBox,Vagrant,Filesystem,Linux)