virtualbox+vagrant学习-1-环境安装及vagrantfile的简单配置-Mac系统

在学习docker-machine时,发现需要使用到虚拟化平台,所以选择了使用virtualBox。

然后后面发现需要使用vagrant来在mac系统中作为虚拟机管理软件,所以下面将会简述我自己学习使用它们的过程:

 

1.virtualbox下载和安装

首先到官网讲virtualbox下载并安装:

https://www.virtualbox.org/wiki/Downloads

安装步骤很简单,就一路继续即可

同时会把VBoxManage安装下来,查看VBoxManage版本:

userdeMBP:~ user$ VBoxManage -v
5.2.22r126460

VBoxManage是VirtualBox的命令行接口。可以使用它在主机操作系统的命令行中完全地控制VirtualBox

 

2.什么是vagrant

Vagrant是一个基于Ruby的工具,用于创建和部署虚拟化开发环境。它使用Oracle的开源VirtualBox虚拟化系统,使用 Chef创建自动化虚拟环境。

Vagrant的运行是需要依赖某个虚拟化平台的,如上面安装的virtualBox

它可以实现的功能有:

  • 建立和删除虚拟机
  • 配置虚拟机运行参数
  • 管理虚拟机运行状态
  • 自动配置和安装开发环境
  • 打包和分发虚拟机运行环境

在Vagrant体系中,有个box(箱子)的概念,这点类似于docker体系中的image(镜像)。基于同一个box,不同的人可以运行得到相同的内容

 

1)下载并安装

https://www.vagrantup.com/downloads.html (选择的是macOS的64位版本)

安装步骤也很简单,一路继续即可

安装好后查看其版本号:

userdeMBP:~ user$ vagrant -v
Vagrant 2.2.2

 查看所有可用命令:

userdeMacBook-Pro:~ user$ vagrant -h
Usage: vagrant [options] <command> [<args>]

    -v, --version                    Print the version and exit. 打印版本并退出
    -h, --help                       Print this help. 打印帮助信息

Common commands:
     box             manages boxes: installation, removal, etc. 管理boxes:安装、移除等操作
     cloud           manages everything related to Vagrant Cloud 管理与vagrant云相关的所有操作
     destroy         stops and deletes all traces of the vagrant machine 停止并删除所有对vagrant机器的追踪
     global-status   outputs status Vagrant environments for this user 输出该用户的vagrant机器的状态
     halt            stops the vagrant machine 停止vagrant机器
     help            shows the help for a subcommand 显示某个子命令的帮助信息
     init            initializes a new Vagrant environment by creating a Vagrantfile 通过创建一个Vagrantfile文件来初始化一个新的vagrant环境
     login           
     package         packages a running vagrant environment into a box 将运行中的环境打包成一个box
     plugin          manages plugins: install, uninstall, update, etc. 管理插件:安装、卸载、更新等操作
     port            displays information about guest port mappings 显示客户端口映射的信息
     powershell      connects to machine via powershell remoting 通过powershell远程连接机器
     provision       provisions the vagrant machine 供应vagrant机器
     push            deploys code in this environment to a configured destination 在这个环境下部署代码到想要配置的目标上
     rdp             connects to machine via RDP 通过RDP连接机器
     reload          restarts vagrant machine, loads new Vagrantfile configuration 重启vagrant机器,下载新的Vagrantfile文件配置信息
     resume          resume a suspended vagrant machine 恢复挂起的vagrant机器
     snapshot        manages snapshots: saving, restoring, etc. 管理快照:保存、恢复等
     ssh             connects to machine via SSH 通过SSH连接机器
     ssh-config      outputs OpenSSH valid configuration to connect to the machine 输出OpenSSH有效配置去连接机器
     status          outputs status of the vagrant machine 输出vagrant机器的状态
     suspend         suspends the machine 挂起机器
     up              starts and provisions the vagrant environment 开启并供应vagrant环境
     upload          upload to machine via communicator 通过通信器上传至机器
     validate        validates the Vagrantfile 验证Vagrantfile文件
     version         prints current and latest Vagrant version 打印当前和最新的vagrant版本
     winrm           executes commands on a machine via WinRM 通过WinRM执行机器上的命令
     winrm-config    outputs WinRM configuration to connect to the machine 输出WinRM配置去连接机器

 

查看现在本机上所拥有的box:

userdeMBP:~ user$ vagrant box list
There are no installed boxes! Use `vagrant box add` to add some.

意思就是我还没有下载任何的box(其实就像是docker中你还没有pull任何的image,所以你运行docker images是什么都没有的状态)

 

2.Getting Started

运行完后,你将在你的virtualBox中完整地运行米的虚拟机——Ubuntu 12.04 LTS 64-bit。你可以通过vagrant ssh命令来ssh连接你的机器,使用vagrant destroy关闭它。

1) 首先初始化

通过创建一个Vagrantfile文件来初始化一个新的vagrant环境

userdeMBP:~ user$ vagrant init hashicorp/precise64
A `Vagrantfile` has been placed in this directory. You are now ready to `vagrant up` your first virtual environment! Please read the comments in the Vagrantfile as well as documentation on`vagrantup.com` for more information on using Vagrant.

Vagrantfile文件内容:

其实下面仅声明了配置的版本号“2”以及box的名称"hashicorp/precise64"

# -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://vagrantcloud.com/search.
  config.vm.box = "hashicorp/precise64"

  # Disable automatic box update checking. If you disable this, then
  # boxes will only be checked for updates when the user runs
  # `vagrant box outdated`. This is not recommended.
  # config.vm.box_check_update = false  //就是让其不会自动查看box是否有更新版本,要用户自己手动运行vagrant box outdated命令去查看

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # NOTE: This will enable public access to the opened port,进行端口映射,将主机的8080端口与虚拟机的80端口映射起来,没有指定IP,则默认使用localhost
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine and only allow access
  # via 127.0.0.1 to disable public access 端口映射,并指定访问的IP地址
  # config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"

  # Create a private network, which allows host-only access to the machine
  # using a specific IP. IP指定的是虚拟机的IP地址,即构建一个私有网络,只允许主机访问该机器
  # config.vm.network "private_network", ip: "192.168.33.10"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network. 创建一个公有网络,匹配网桥网络。这样该机器就能够在你的网络中作为另一个物理设备出现
  # config.vm.network "public_network"

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options. 与虚拟机共享文件夹。第一个地址是主机实际文件夹地址(默认为本机vagrantfile所在目录),第二个是虚拟机中用来挂载的文件夹(默认为/vagrant)。
  # config.vm.synced_folder "../data", "/vagrant_data"

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  # config.vm.provider "virtualbox" do |vb| 默认使用的虚拟化平台是virtualbox
  #   # Display the VirtualBox GUI when booting the machine 当启动机器的时候显示VirtualBox的图形化界面
  #   vb.gui = true
  #
  #   # Customize the amount of memory on the VM:定制虚拟机的内存
  #   vb.memory = "1024"
  # end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

  # Enable provisioning with a shell script. Additional provisioners such as
  # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
  # documentation for more information about their specific syntax and use.
  # config.vm.provision "shell", inline: <<-SHELL  一些想要在虚拟机启动后执行的shell脚本,如下面就进行了apt-get的更新和apache2的安装
  #   apt-get update
  #   apt-get install -y apache2
  # SHELL
end

可以在vagrant cloud上找到该box,以及它的Vagrantfile内容:

 

2)启动vagrant

userdeMBP:~ user$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'hashicorp/precise64' could not be found. Attempting to find and install... 没有在本地找到hashicorp/precise64这个box
    default: Box Provider: virtualbox 默认使用的虚拟化平台是virtualbox
    default: Box Version: >= 0
==> default: Loading metadata for box 'hashicorp/precise64'
    default: URL: https://vagrantcloud.com/hashicorp/precise64
==> default: Adding box 'hashicorp/precise64' (v1.1.0) for provider: virtualbox
    default: Downloading: https://vagrantcloud.com/hashicorp/boxes/precise64/versions/1.1.0/providers/virtualbox.box
==> default: Box download is resuming from prior download progress
    default: Download redirected to host: vagrantcloud-files-production.s3.amazonaws.com
==> default: Successfully added box 'hashicorp/precise64' (v1.1.0) for 'virtualbox'!
==> default: Importing base box 'hashicorp/precise64'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'hashicorp/precise64' is up to date...
==> default: Setting the name of the VM: user_default_1545626647357_52059
Vagrant is currently configured to create VirtualBox synced folders with
the `SharedFoldersEnableSymlinksCreate` option enabled. If the Vagrant
guest is not trusted, you may want to disable this option. For more
information on this option, please refer to the VirtualBox manual: 该警告就是是否共享文件夹,默认是共享的,可以按照下面的方式去取消共享

  https://www.virtualbox.org/manual/ch04.html#sharedfolders

This option can be disabled globally with an environment variable:

  VAGRANT_DISABLE_VBOXSYMLINKCREATE=1

or on a per folder basis within the Vagrantfile:

  config.vm.synced_folder '/host/path', '/guest/path', SharedFoldersEnableSymlinksCreate: false 
==> 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: Forwarding ports... 映射的端口
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM... 启动了虚拟机
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222 可以使用vagrant ssh连接虚拟机
    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: The guest additions on this VM do not match the installed version of
    default: VirtualBox! In most cases this is fine, but in rare cases it can
    default: prevent things such as shared folders from working properly. If you see
    default: shared folder errors, please make sure the guest additions within the
    default: virtual machine match the version of VirtualBox you have installed on
    default: your host and reload your VM.
    default: 
    default: Guest Additions Version: 4.2.0
    default: VirtualBox Version: 5.2
==> default: Mounting shared folders... 挂载共享文件夹
    default: /vagrant => /Users/user 虚拟机上的/vagrant文件夹将于本机的/Users/user共享

 查看此时本机的box:

userdeMBP:~ user$ vagrant box list
hashicorp/precise64 (virtualbox, 1.1.0)

然后现在打开virtualBox工具,可以看见果然开启了一个虚拟机:

然后在我本地的共享文件夹下会生成一个VirtualBox VMs文件夹:

存放着我打开的虚拟机及其文件:

打开虚拟机,用户名和密码都是vagrant:

也可以直接在终端使用vagrant ssh来连接虚拟机:

userdeMBP:~ user$ vagrant ssh
Welcome to Ubuntu 12.04 LTS (GNU/Linux 3.2.0-23-generic x86_64)

 * Documentation:  https://help.ubuntu.com/
New release '14.04.5 LTS' available.
Run 'do-release-upgrade' to upgrade to it.

Welcome to your Vagrant-built virtual machine.
Last login: Mon Dec 24 06:58:45 2018
vagrant@precise64:~$

使用ls /vagrant 命令就能够看见本机共享文件夹中的内容了

退出:

vagrant@precise64:~$ logout
Connection to 127.0.0.1 closed.

 到这里,简单的使用过程就结束了

 

3.vagrantfile中提及的基本的相关配置信息

1)使用命令添加box:

userdeMBP:box user$ vagrant box add ubuntu/trusty64
==> box: Loading metadata for box 'ubuntu/trusty64'
    box: URL: https://vagrantcloud.com/ubuntu/trusty64
==> box: Adding box 'ubuntu/trusty64' (v20181207.0.2) for provider: virtualbox
    box: Downloading: https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20181207.0.2/providers/virtualbox.box
...

但是这个过程一般要花费很长的时间,这里用户名为ubuntu,box名为trusty64

然后当我们想要使用上面添加的box时,vagrantfile中应写成:

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/trusty64" #指明使用的box
 config.vm.box_version = "v20181207.0.2" #指明版本
  config.vm.box_url = "https://vagrantcloud.com/ubuntu/trusty64" #指明下载的地址
end

 

2)共享文件夹

在vagrantfile中添加语句:

与虚拟机共享文件夹。第一个地址是主机实际文件夹地址(默认为本机vagrantfile所在目录),第二个是虚拟机中用来挂载的文件夹(默认为/vagrant)

config.vm.synced_folder "../data", "/vagrant_data"

 

3)Provisioning 预配置

即可以在vagrantfile指明在使用vagrant up启动虚拟机时,能够指明要运行的shell脚本来对环境自动进行前期的准备,而不用手动操作,如文件bootstrap.sh

#!/usr/bin/env bash
apt-get update #更新apt-get
apt-get install -y apache2 #安装apache2

⚠️bootstrap.sh文件要放和vagrantfile文件放在同一个目录下

然后在vagrantfile中写上:

config.vm.provision :shell, path: "bootstrap.sh"

或者直接在vagrantfile中写上:

config.vm.provision "shell", inline: <<-SHELL
   apt-get update
   apt-get install -y apache2
SHELL

如果你的Provisioning语句是新添加的,你已经启动过虚拟机了,那么你可以运行:

vagrant reload --provision

它将重启虚拟机,并运行上面的命令即可

 

4)网络

1》端口映射

config.vm.network :forwarded_port, guest: 80, host: 4567

将本机的4567端口映射到虚拟机的80端口,这样在本机的浏览器中调用http://127.0.0.1:4567时,访问的其实是虚拟机80端口提供的服务

⚠️在vagrantfile中新添的配置要运行vagrant reload或vagrant up命令来重启虚拟机,配置才能有效

 

当然,你也是可以指定使用的ip地址的,默认是localhost,即127.0.0.1:

config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "192.168.0.1"

 

2》主机模式

1〉公有网络

config.vm.network "public_network"

创建一个公有网络,匹配网桥网络。这样该虚拟机就能够在你的网络中作为另一个物理设备出现

2>私有网络

config.vm.network "private_network", ip: "192.168.33.10"

IP指定的是虚拟机的IP地址,主机可以通过这个IP访问客户机网络。即构建一个私有网络,只允许主机访问该机器

5)Providers

默认使用的Providers是virtualBox,其实其还能使用在VMware, AWS上,不需要在vagrantfile进行配置,直接在运行时声明即可

1》vmware

$ vagrant up --provider=vmware_fusion

2云平台

$ vagrant up --provider=aws

 

上面只是使用vagrant的简单讲解,更详细内容请往下看

posted @ 2019-01-02 17:00  慢行厚积  阅读(5660)  评论(1编辑  收藏  举报