如何使用vagrant搭建一个和生产环境对等的本地环境?

分享一篇简短的实践文章,明天就是五一假期了,祝大家玩得开心。

解决的问题

笔者需要部署一个 etcd 集群,并非使用 goreman 工具部署的伪集群。为了与真实环境对等,需要用到三台机器,然而笔者手上只有一台主机,Centos 系统,配置为 8G 双核。由此想到在单机 Centos 再启动虚拟机的想法。

环境准备

vagrant 的使用需要结合 VirtualBox,我们我们准备这两个软件的安装源,以及用到的 centos7 镜像:

<code> 
https: 

 
https: 

 
http:/<code>

笔者下载的是最新的版本,官网的下载速度实在慢(有需要可以联系笔者获取下载好的安装包),文件如下:

<code>$ ls 

CentOS

-7

-x86_64-Vagrant

-2002

_01.VirtualBox.box  VirtualBox

-6.1

-6.1

.6

_137129_el7

-1.

x86_64.rpm            vagrant_2

.2

.7

_x86_64.rpm                                     /<code>

安装

<code>$ yum  -y  localinstall VirtualBox

-6.1

-6.1

.6

_137129_el7

-1.

x86_64.rpm vagrant_2

.2

.7

_x86_64.rpm/<code>

如上的命令,即安装好 vagrant 和 VirtualBox。

初始化

vagrant 的常用命令如下,用于管理boxes的命令,比如添加、删除等等。此命令的功能主要通过以下子命令完成:

如何使用vagrant搭建一个和生产环境对等的本地环境?

<code> 
vagrant  box 

add

  CentOS

-7

-x86_64-Vagrant

-2002

_01.VirtualBox.box --name centos7 vagrant init centos7/<code>

初始化的步骤,会生成一个 Vagrantfile,即配置文件。

<code>$ vagrant init centos7

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./<code>

Vagrantfile 配置

常用的配置如下所示:

  • config.vm.box:该名称是再使用 vagrant init 中后面跟的名字
  • config.vm.hostname:配置虚拟机主机名
  • config.vm.network:这是配置虚拟机网络,由于比较复杂,我们其后单独讨论
  • config.vm.synced_folder:除了默认的目录绑定外,还可以手动指定绑定
  • config.ssh.username:默认的用户是vagrant,从官方下载的box往往使用的是这个用户名。如果是自定制的box,所使用的用户名可能会有所不同,通过这个配置设定所用的用户名。
  • config.vm.provision:我们可以通过这个配置在虚拟机第一次启动的时候进行一些安装配置

还有更详细的配置,参见:
https://www.vagrantup.com/docs/vagrantfile/。笔者使用的配置如下:

<code>Vagrant.configure(

"2"

do

 

|config|

  config.vm.box = 

"centos7"

   config.vm.network 

"public_network"

ip:

 

"192.168.0.5"

   config.vm.provider 

"virtualbox"

 

do

 

|vb|

           vb.gui = 

false

           vb.memory = 

"1024"

   

end

end

/<code>

可以看到,配置比较简单,使用桥接的方式指定了网络,设置关闭 gui,并限制内存为 1GB。

启动

<code>$ vagrant  up

The

 provider 'virtualbox' that was requested to back the machine '

default

is

 reporting that it isn't usable on this system. 

The

reason 

is

 shown below:

VirtualBox

 

is

 complaining that the kernel module 

is

 not loaded. 

Please

run `

VBoxManage

 --version` or 

open

 the 

VirtualBox

 

GUI

 to see the error message which should contain instructions on how to fix this error./<code>

参考,
virtualbox-is-complaining-that-the-kernel-module-is-not-loaded。原因是 vagrant 依赖 kernel-devel gcc make perl, 启动 kernel-devel ,最好按照 vagrant 的提示进行安装和正在使用内核版本一直的库。

通过uname查看内核版本:

<code> 

$

 

uname

 

-a

 

Linux

 

aoho

 

3.10

.0

-1062.1

.2

.el7.x86_64

 /<code>

因此我们需要安装相应的包:

<code>

kernel-devel-3

.10

.0-1062

.1

.2

.el7

.x86_64

.rpm

/<code>

在官网下载了对应的包,并安装。启动 vagrant:

<code> 

vagrant

 up vagrant ssh/<code>

大功告成!


分享到:


相關文章: