Skip to content

Instantly share code, notes, and snippets.

@willnss
Last active June 23, 2016 12:15
Show Gist options
  • Save willnss/ff2e15b5a1d5fc783d8453f495e5c522 to your computer and use it in GitHub Desktop.
Save willnss/ff2e15b5a1d5fc783d8453f495e5c522 to your computer and use it in GitHub Desktop.

Instalando mongodb em uma máquina virtual com o Vagrant :shipit: :shipit:

Requisitos: virtualbox + extension pack e o vagrant com versões compatíveis

Obs: arquivos sh, vagrantfile logo após este markdown

Acessar o terminal ou cmd e adicionar a box desejada a se trabalhar, optei por utilizar a ubuntu/trusty32. Outras podem ser obtidas em https://atlas.hashicorp.com/boxes/search Caso já possua uma box pode pular para o próximo passo.

vagrant box add ubuntu/trusty32

Acessar o diretório em que deseja iniciar o acesso a maquina virtual e rodar o comando:

vagrant init

Isso irá criar o arquivo Vagrantfile contendo um script ruby com definições da máquina que será criada. Procure a configuração config.vm.box e informe o nome de sua box. Obs: Todos os comandos referente a esta máquina sempre rodar na pasta que a mesma foi iniciada.

config.vm.box = "ubuntu/trusty64"

Para que o mongo esteja acessível fora da máquina virtual, encontre a seção comentada onde esta definido o encaminhamento de portas do guest (máquina virtual) para o host (sistema opercional atual) e defina logo abaixo o encaminhamento da porta default do mongod e mongos (neste caso 27017).

#  config.vm.network "forwarded_port", guest: 80, host: 8080 <- seção original do Vagrantfile
config.vm.network "forwarded_port", guest: 27017, host: 27017 # nova linha adicionada

Caso queira definir um nome amigável para máquina inclua o seguinte trecho.

config.vm.provider "virtualbox" do |v|
    v.name = "vm-mongo"
end

Para automatizar o processo de instalação de uma instância do mongodb crie um arquivo na mesma pasta em que o Vagrantfile foi criado com o nome provision-mongo.sh com o seguinte conteúdo:

#!/usr/bin/env bash

locale-gen UTF-8

apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 && \
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | tee /etc/apt/sources.list.d/mongodb.list && \
apt-get update && \
apt-get install mongodb-org=2.6.4 mongodb-org-server=2.6.4 mongodb-org-shell=2.6.4 mongodb-org-mongos=2.6.4 mongodb-org-tools=2.6.4 && \
echo "mongodb-org hold" | dpkg --set-selections && \
echo "mongodb-org-server hold" | dpkg --set-selections && \
echo "mongodb-org-shell hold" | dpkg --set-selections && \
echo "mongodb-org-mongos hold" | dpkg --set-selections && \
echo "mongodb-org-tools hold" | dpkg --set-selections && \
sed -i '/bind_ip = 127.0.0.1/,/bind_ip\ =\ 127\.0\.0\.1/s/^/#/' /etc/mongod.conf && \
service mongod restart

Voltando ao Vagrantfile, encontre a seção (# Enable provisioning with a shell script. Additional provisioners such as) e acima este trecho comentado inclua.

config.vm.provision :shell, path: "provision-mongo.sh"

De volta ao terminal/cmd execute:

vagrant up

Aguarde a criação da máquina e após o boot o vagrant iniciará a instalação do mongo e iniciará o serviço.

Resolução problemas :shipit:

Obs: Caso tenha problemas e obtenha a mensagem 'The guest additions on this VM do not match the install version of VirtualBox' instale o plugin abaixo pelo terminal/cmd e tente novamente

vagrant plugin install vagrant-vbguest

Em seguida caso tenha tido o problema da obserevação acima o comando abaixo para forçar a execução do shell para instalar o mongo:

vagrant up --provision

Após término do processo o próprio script shell iniciará o mongod que disponiblizará o server através do endereço local e porta 27017.

Para suspender a máquina após o uso e salvar o estado atual rode:

vagrant suspend

Para restaurar a máquina para uso novamente rode:

vagrant resume

Para acessar a máquina via terminal no Mac e Linux (͡° ͜ʖ ͡°)

vagrant ssh

Para acessar a máquina via terminal no Windows

:shipit: Instale algum cliente SSH, exemplo: putty.exe. Para se conectar utilize o IP/porta 172.0.0.1:2222 e indique a chave privada insecure_private_key localizada na pasta C:/Users/seu usuário/.vagrant.d

Testando a instância a partir do host :shipit:

Com a instância do mongo rodando realize o teste com algum client do mongodb, ex: mongoose para nodejs http://mongoosejs.com/docs/

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log('conectamos');
});

Referência: https://gist.github.com/trumbitta/9eed0c3ce369c9c4a01b

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('conectamos');
});
#!/usr/bin/env bash
# Referência: <https://gist.github.com/trumbitta/9eed0c3ce369c9c4a01b>
locale-gen UTF-8
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 && \
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | tee /etc/apt/sources.list.d/mongodb.list && \
apt-get update && \
apt-get install mongodb-org=2.6.4 mongodb-org-server=2.6.4 mongodb-org-shell=2.6.4 mongodb-org-mongos=2.6.4 mongodb-org-tools=2.6.4 && \
echo "mongodb-org hold" | dpkg --set-selections && \
echo "mongodb-org-server hold" | dpkg --set-selections && \
echo "mongodb-org-shell hold" | dpkg --set-selections && \
echo "mongodb-org-mongos hold" | dpkg --set-selections && \
echo "mongodb-org-tools hold" | dpkg --set-selections && \
sed -i '/bind_ip = 127.0.0.1/,/bind_ip\ =\ 127\.0\.0\.1/s/^/#/' /etc/mongod.conf && \
service mongod restart
# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
# The most common configuration options are documented and commented below.
# For a complete reference, please see the online documentation at
# https://docs.vagrantup.com.
# Every Vagrant development environment requires a box. You can search for
# boxes at https://atlas.hashicorp.com/search.
config.vm.box = "ubuntu/trusty32"
# Disable automatic box update checking. If you disable this, then
# boxes will only be checked for updates when the user runs
# `vagrant box outdated`. This is not recommended.
# config.vm.box_check_update = false
# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine. In the example below,
# accessing "localhost:8080" will access port 80 on the guest machine.
# config.vm.network "forwarded_port", guest: 80, host: 8080
config.vm.network "forwarded_port", guest: 27017, host: 27017
# Create a private network, which allows host-only access to the machine
# using a specific IP.
# config.vm.network "private_network", ip: "192.168.33.10"
# Create a public network, which generally matched to bridged network.
# Bridged networks make the machine appear as another physical device on
# your network.
# config.vm.network "public_network"
# Share an additional folder to the guest VM. The first argument is
# the path on the host to the actual folder. The second argument is
# the path on the guest to mount the folder. And the optional third
# argument is a set of non-required options.
# config.vm.synced_folder "../data", "/vagrant_data"
# Provider-specific configuration so you can fine-tune various
# backing providers for Vagrant. These expose provider-specific options.
# Example for VirtualBox:
#
# config.vm.provider "virtualbox" do |vb|
# # Display the VirtualBox GUI when booting the machine
# vb.gui = true
#
# # Customize the amount of memory on the VM:
# vb.memory = "1024"
# end
#
# View the documentation for the provider you are using for more
# information on available options.
config.vm.provider "virtualbox" do |v|
v.name = "vm-mongo"
end
# Define a Vagrant Push strategy for pushing to Atlas. Other push strategies
# such as FTP and Heroku are also available. See the documentation at
# https://docs.vagrantup.com/v2/push/atlas.html for more information.
# config.push.define "atlas" do |push|
# push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME"
# end
config.vm.provision :shell, path: "provision-mongo.sh"
# Enable provisioning with a shell script. Additional provisioners such as
# Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
# documentation for more information about their specific syntax and use.
# config.vm.provision "shell", inline: <<-SHELL
# apt-get update
# apt-get install -y apache2
# SHELL
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment