Vagrant

Теория: Инициализация

Vagrant предполагает, что мы создаем отдельную конфигурацию на каждый проект, а не одну на все. Инициализация выполняется в директории соответствующего проекта:

vagrant init ubuntu/focal64

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.

В результате выполнения этой команды Vagrant создаст файл Vagrantfile. Внутри файла описана конфигурация виртуальной машины на языке Ruby. Не страшно, если вы не знакомы с ним, содержимое файла интуитивно понятно, а документация Vagrant достаточно подробна.

Vagrant.configure('2') do |config|
  config.vm.box = 'ubuntu/focal64'
end

Vagrantfile нужно добавить в git-репозиторий, благодаря этому мы получим одну конфигурацию для всех разработчиков. Помимо Vagrantfile, в процессе работы Vagrant создаст директорию .vagrant в корне проекта. Эту директорию нужно добавить в .gitignore.

Запуск и остановка

Старт выполняется командой vagrant up. Она скачивает образ ubuntu/focal64, создает на его основе виртуальную машину внутри VirtualBox и запускает ее. Первый запуск займет какое-то время пока все скачается и настроится. Затем команда начнет отрабатывать за десятки секунд, время нужное на старт операционной системы внутри виртуальной машины.

vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'ubuntu/focal64'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'ubuntu/focal64' version '20211211.0.0' is up to date...
==> default: Setting the name of the VM: hexlet-vagrant_default_1639729176382_63252
==> 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: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    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: 6.0.0 r127566
    default: VirtualBox Version: 6.1
==> default: Mounting shared folders...
    default: /vagrant => /home/hexlet/hexlet-vagrant

Запущенная машина потребляет немало ресурсов. После работы с проектом имеет смысл останавливать машину с помощью команды vagrant halt.

vagrant halt
==> default: Attempting graceful shutdown of VM...

Чтобы узнать текущий статус машины, запущена она или нет, можно воспользоваться командой vagrant status:

vagrant status
Current machine states:

default                   running (virtualbox)

The VM is running. To stop this VM, you can run `vagrant halt` to
shut it down forcefully, or you can run `vagrant suspend` to simply
suspend the virtual machine. In either case, to restart it again,
simply run `vagrant up`.

Для полного уничтожения машины есть команда vagrant destroy. После этого ее можно создать заново командой vagrant up.

vagrant destroy
    default: Are you sure you want to destroy the 'default' VM? [y/N] y
==> default: Forcing shutdown of VM...
==> default: Destroying VM and associated drives...

Рекомендуемые программы