How do I provision a Dockerfile from Vagrant

2019-03-15 01:23发布

问题:

How can I start the provisioning of Docker via an external Dockerfile? My Vagrantfile looks like this at the moment

Vagrant.configure("2") do |config|
  config.vm.box = "precise64"
  config.vm.define :server_infrastructure do |t|
  end

  config.vm.provision "docker" do |d|
    d.pull_images "ubuntu"
    #how does the below work?
    #d.build "new-container-name" "local-docker-file-name"
  end
end

Your help is greatly appreciated

回答1:

An option for the Docker provisioner to build images was added in v1.6.0. Download the latest version from the Vagrant website.

Once you've done that, put a Dockerfile next to your Vagrantfile. Add this to your Vagrantfile:

config.vm.provision "docker" do |d|
  d.build_image "/vagrant", args: "-t my-name/my-new-image"
  d.run "my-name/my-new-image"
end

Now your Docker image will be built and run with vagrant up.



回答2:

one workaround is through shell provisioning:

config.vm.provision "shell", inline: "docker build -t username/image /vagrant; docker run -d username/image"


回答3:

For docker to build an image from a dockerfile, dockerfile in question must be presented in the guest machine and the way to ensure this is to use shared folder feature of vagrant.

By default vagrant mounts your project root folder to the new vm under the name /vagrant. But in your case i suggest you share a different folder and put your dockerfiles there. Also by sharing a different folder you can make sure that your dockerfiles are seen read-only by the guest machine.

Now suppose you create a new folder in your projects root directory named "docker" and put your dockerfiles in it. Now if you mount this folder to your guest machine and point docker to use that file you are all set. if you add these lines to your vagrant file it will work as expected. config.vm.synced_folder "docker/", "/docker_builds", create: true, mount_options: ["ro"] config.vm.provision "docker" do |d| d.build_image "/docker_builds", args: "-t my-name/my-new-image" d.run "my-name/my-new-image" end