0%

Vagrant基本命令

vagrant 使用

init centos

centos7 box 下载地址centos7

添加vagrant box到box list

1
vagrant box add centos7 Vagrant-CentOS-7.box

初始化一个虚拟机使用刚才添加的vagrant box

1
2
3
mkdir centos
cd centos
vim Vagrantfile

添加下面内容到Vagrantfile中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.require_version ">= 1.6.0"

boxes = [
{
:name => "docker-node1",
:eth1 => "192.168.205.10",
:mem => "1024",
:cpu => "1"
},
{
:name => "docker-node2",
:eth1 => "192.168.205.11",
:mem => "1024",
:cpu => "1"
}
]

Vagrant.configure(2) do |config|

config.vm.box = "centos7"

boxes.each do |opts|
config.vm.define opts[:name] do |config|
config.vm.hostname = opts[:name]
config.vm.provider "vmware_fusion" do |v|
v.vmx["memsize"] = opts[:mem]
v.vmx["numvcpus"] = opts[:cpu]
end

config.vm.provider "virtualbox" do |v|
v.customize ["modifyvm", :id, "--memory", opts[:mem]]
v.customize ["modifyvm", :id, "--cpus", opts[:cpu]]
end

config.vm.network :private_network, ip: opts[:eth1]
end
end

config.vm.provision "shell", privileged: true, path: "./setup.sh"

end

install docker的setup.sh文件

在当前目录创建setup.sh文件并添加如下内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#/bin/sh

# install some tools
sudo yum install -y git vim gcc glibc-static telnet bridge-utils

# install docker
curl -fsSL get.docker.com -o get-docker.sh
sh get-docker.sh

# start docker service
sudo groupadd docker
sudo usermod -aG docker vagrant
sudo systemctl start docker

rm -rf get-docker.sh

启动安装

1
vagrant up

vagrant 报unknown filesystem type ‘vboxsf’ 解决方案

1
2
vagrant plugin install vagrant-vbguest
vagrant destroy && vagrant up

init ubuntu

使用清华源

ubuntu18的box,终端运行如下命令

1
2
3
vagrant box add \
https://mirrors.tuna.tsinghua.edu.cn/ubuntu-cloud-images/bionic/current/bionic-server-cloudimg-amd64-vagrant.box \
--name ubuntu/bionic

Vagrantfile这样写:

1
2
3
...
config.vm.box = "ubuntu/bionic"
...

接着就是vagrant up && vagrant ssh

基本命令

列出所有Box

1
vagrant box list

添加一个Box

1
vagrant box add [options] <name, url, or path

可以从https://app.vagrantup.com/boxes/search下载各种Vagrant映像文件

1
vagrant box add ubuntu/trusty64

通过指定的URL添加远程box

1
vagrant box add https://atlas.hashicorp.com/ubuntu/boxes/trusty64

添加一个本地box

1
vagrant box add {box_name} {file_path}

初始化一个新VM

1
vagrant init ubuntu/trustry64

此命令会在当前目录创建一个名为Vagrantfile的配置文件,内容大致如下:

1
2
3
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/trusty64"
end

初始化一个新VM

1
vagrant up

启用SSH登陆VM

1
vagrant ssh <node_name>

如果需要从虚拟机中退出,直接在虚拟机中的命令行输入exit命令即可

查看VM当前的状态

进入Vagrantfile配置文件所在的目录,执行以下命令:

1
vagrant status

关闭VM

1
vagrant halt

销毁VM

1
vagrant destory [name|id]