Learn to Manage VM in 5 mins with Vagrant up !

Learn to Manage VM in 5 mins with Vagrant up !

DevOps Jun 18, 2023

Vagrant is less awkward way to manage VM. Easily up and running.

VM Folder

Making folder for your VM and run vagrant init

vagrant-folder
|__ Vagrantfile
|__ other_file_1
|__ other_file_2
|__ other_file_3

Stuff in this folder will be synced to /vagrant folder in the Vagrant machine

Up, Connect, Suspend, Halt, Destroy

Start your VM with

$ vagrant up
$ vagrant ssh        // connect to VM
$ vagrant suspend    // pause
$ vagrant halt       // shutdown
$ vagrant destroy    // remove VM and stuff inside

Startup script

We will learning to config stuff machine do when it starts by setup Apache server that send back ‘Hello’ html.

Go to Vagrantfile uncomment the provision line

Then add <h1>hello</h1> to the Apache directory.

config.vm.provision "shell", inline: <<-SHELL
   apt-get update
   apt-get install -y apache2
++ echo "<h1>hello</h1>" > /var/www/html/index.html
SHELL

Any change in config need vagrant reload to take an effect

For change in provisioning block need extra --provision flag

$ vagrant reload --provision

Access from Host Machine

Now the server is running inside the VM (you can ssh inside to see that)

To expose the port to Host machine uncommend the following block

config.vm.network "forwarded_port", guest: 80, host: 8080

Then $ vagrant reload

Then go to your browser localhost:8080 and here you go. It’s working and send back ‘Hello’.

Hope this help and see you in the next tutorial !

Tags

TeamCMD

We are CODEMONDAY team and provide a variety of content about Business , technology, and Programming. Let's enjoy it with us.