使用vagrant+virtualbox搭建跨平臺開發環境

相關參數

  • 目錄地址: (本機目錄) D:\web => /www/ (對應虛擬機目錄)html

準備工做

安裝vagrant

https://www.vagrantup.com/downloads.htmllinux

更改vagrant配置文件的位置

若是C盤空間足夠,此步可不操做git

將 C:\Users\user_name\.vagrant.d 移動到新的位置

新建環境變量VAGRANT_HOME,並指向新路徑

安裝virtualbox

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

下載centos7的vagrant box到你想掛載的目錄(好比 D:\web),用vagarant鏡像下載會很是慢,推薦用下面的連接下載
下載地址:
cloud.centos.orgweb

這個box是純淨版的
其它鏡像:
http://cloud.centos.org/centos/7/vagrant/x86_64/images/shell

更改virtaulbox虛擬機默認位置

  • 打開 VirtualBox 程序,點擊管理/全局設定菜單項windows

  • 將常規欄裏的默認虛擬電腦位置改成其餘磁盤下的路徑centos

  • 從新啓動VirtualBox程序app

使用vagrant

vagrant plugin install vagrant-vbguest

vagrant  box  add  centos7.2  virtualbox.box
#命令解釋:vagrant box add爲載入鏡像命令,centos7.2爲載入後的鏡像名稱,virtualbox.box爲box文件名

vagrant  init  centos7.2  #根據鏡像初始化一個虛擬機

# 修改本機目錄下的Vagrantfile文件 , 將config.vm.network "public_network"前的註釋刪除並保存

vagrant  up    #在本機目錄下執行該命令,啓動虛擬機

vagrant vbguest --auto-reboot

vagrant package # 打包系統生成package.box文件

默認帳號 vagrant 密碼 vagrant ;
root帳號的默認密碼vagrant;ssh

執行完vagrant up後,虛擬機就啓動了

虛擬機能夠直接用VirtualBox管理,也能夠用Xshell鏈接虛擬機進行管理

也能夠在該目錄下執行 vagrant ssh 連入虛擬機(windows須要安裝shell工具)

此時你已經有了一個centOS7.2的虛擬機,接下來就能夠用它來搭建各類服務來運行你的項目。

以後每次只需在掛載目錄下執行vagrant up就能夠了

vagrantfile配置

建議在vagrantfile中配置

config.vm.network "private_network", type: "dhcp"

config.vbguest.auto_update = false

# do NOT download the iso file from a webserver
config.vbguest.no_remote = true

config.vm.synced_folder ".", "/vagrant",owner: "vagrant",group: "vagrant",mount_options:["dmode=777","fmode=777"]

其它配置詳見
《官方文檔》 《Vagrantfile 配置》

常見問題

共享目錄沒法掛載

報錯信息

Vagrant was unable to mount VirtualBox shared folders. This is usually
because the filesystem "vboxsf" is not available. This filesystem is
made available via the VirtualBox Guest Additions and kernel module.
Please verify that these guest additions are properly installed in the
guest. This is not a bug in Vagrant and is usually caused by a faulty
Vagrant box. For context, the command attempted was:

mount -t vboxsf -o uid=1000,gid=1000 vagrant /vagrant

The error output from the command was:

/sbin/mount.vboxsf: mounting failed with the error: No such device

解決方案

方法1 安裝vagrant插件

vagrant plugin install vagrant-vbguest
vagrant vbguest --auto-reboot
vagrant vbguest --status   #查看vbguest運行狀態

方法2 更新vagrant和virtualbox

更新vagrant以後須要更新vagrant插件

vagrant plugin update

方法三 從新安裝vboxadd

VBoxGuestAdditions的位置

for linux : /usr/share/virtualbox/VBoxGuestAdditions.iso
for Mac : /Applications/VirtualBox.app/Contents/MacOS/VBoxGuestAdditions.iso
for Windows : %PROGRAMFILES%/Oracle/VirtualBox/VBoxGuestAdditions.iso

使用vitualbox掛載上面的iso虛擬光驅

#進入虛擬機
vagrant ssh
#若是這個命令沒法進入的話,就用virtualbox進入

#*號爲版本號
cd /opt/VBoxGuestAdditions-*/init
sudo ./vboxadd setup # 若是不能setup就yum update

#退出虛擬機
exit

#重啓虛擬機
vagrant reload
相關文章
相關標籤/搜索