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的簡單講解,更詳細內容請往下看


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM