-
Vagrantfile
In the project root directory, create a
Vagrantfile
with the following content:Vagrant.configure("2") do |config| # Base box config.vm.box = "geerlingguy/ubuntu2004" # Network configuration config.vm.network "forwarded_port", guest: 3000, host: 3000 config.vm.network "forwarded_port", guest: 5000, host: 5000 config.vm.network "forwarded_port", guest: 27017, host: 27017 # VM resources config.vm.provider "virtualbox" do |vb| vb.memory = "2048" vb.cpus = 2 end # Sync the current directory with the VM config.vm.synced_folder ".", "/vagrant" # Provision the VM with Ansible config.vm.provision "ansible" do |ansible| ansible.playbook = "playbook.yml" end end
This Vagrantfile sets up a Ubuntu 20.04 VM with Docker, Docker Compose, and forwards the necessary ports for the frontend, backend, and MongoDB.
-
Ansible Playbook
Create an
ansible/playbook.yml
with tasks to set up Docker and the application:--- - hosts: all become: yes tasks: - name: Update APT package index apt: update_cache: yes - name: Install required packages apt: name: - apt-transport-https - ca-certificates - curl - software-properties-common state: present - name: Add Docker's official GPG key apt_key: url: https://download.docker.com/linux/ubuntu/gpg state: present - name: Add Docker's APT repository apt_repository: repo: deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable state: present - name: Install Docker apt: name: docker-ce state: present - name: Install Docker Compose apt: name: docker-compose state: present - name: Add vagrant user to the docker group user: name: vagrant groups: docker append: yes - name: Copy docker-compose.yml to VM copy: src: /vagrant/docker-compose.yml dest: /home/vagrant/docker-compose.yml - name: Run Docker Compose shell: docker-compose up -d args: chdir: /home/vagrant
This playbook installs Docker, Docker Compose, and runs the application using
docker-compose
.
-
Start the Vagrant Environment
To start the Vagrant environment, run the following command in the project root directory:
vagrant up
This command will create and configure the VM based on the
Vagrantfile
andAnsible
playbook. -
Access the VM
SSH into the VM with:
vagrant ssh
-
Check Running Containers
Once inside the VM, you can verify the running Docker containers:
docker ps
This command should list the frontend, backend, and MongoDB containers.
-
Stop the Vagrant Environment
To stop the Vagrant VM, use the following command:
vagrant halt
-
Destroy the Vagrant Environment
If you need to destroy the VM and start fresh, use:
vagrant destroy
By using Vagrant, you can easily set up a development environment that mimics the production setup. This ensures consistency and helps in testing the application locally. The combination of Vagrant and Docker provides a robust solution for development and testing.