Skip to content

Instantly share code, notes, and snippets.

@tuanpht
Last active June 26, 2022 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuanpht/aea9a7ad3e34eb7323501efea6192316 to your computer and use it in GitHub Desktop.
Save tuanpht/aea9a7ad3e34eb7323501efea6192316 to your computer and use it in GitHub Desktop.
Create local VPS with vagrant

Intro

A VPS is just a server machine (Ubuntu, CentOS,...) on the Internet which you can SSH into.

A local VPS is a VPS but running on your local machine thanks to Virtual Machine technology. It's very simple to create a VM thanks to Vagrant, so that you can use it to play with SSH, test deployment, test Ansible playbook,...

Setup

  1. Install VirtualBox
  2. Install Vagrant
  3. Create a virtual machine, for example: Ubuntu 20.04
$ mkdir ubuntu-20.04
$ vagrant init ubuntu/focal64
$ vagrant up

In this case ubuntu/focal64 is called a box which represents for Ubuntu 20.04, you can find other box here.

SSH into your local vm:

vagrant ssh

Some deployment tools such as Capistrano, PHP Deployer would require a SSH connection, but they don't know about vagrant ssh, so you need to extract SSH config from vagrant so that you can do a normal ssh command, e.g. ssh local-vm. To do so, run this command:

$ vagrant ssh-config

Host default
  HostName 127.0.0.1
  User vagrant
  Port 2222
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile /home/ubuntu/vm/ubuntu-20.04/.vagrant/machines/default/virtualbox/private_key
  IdentitiesOnly yes
  LogLevel FATAL

Update the ouput above a bit and put it in your ~/.ssh/config:

Host local-vps-ubuntu-20.04
  HostName 127.0.0.1
  User vagrant
  Port 2222
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile /home/ubuntu/vm/ubuntu-20.04/.vagrant/machines/default/virtualbox/private_key
  IdentitiesOnly yes
  LogLevel FATAL

And now we have local-vps-ubuntu-20.04 you can use ssh command:

ssh local-vps-ubuntu-20.04

Each time you want to turn on your local vps, you need cd to the vagrant folder and run:

cd /home/ubuntu/vm/ubuntu-20.04
vagrant up

Alternately, you can use this single command anywhere:

VAGRANT_CWD=/home/ubuntu/vm/ubuntu-20.04 vagrant up

When you change the Vagrantfile, for example open a port from your local vps, you need to reload vagrant:

VAGRANT_CWD=/home/ubuntu/vm/ubuntu-20.04 vagrant reload

When you want to delete VM and delete all data inside it, you can run:

VAGRANT_CWD=/home/ubuntu/vm/ubuntu-20.04 vagrant destroy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment