QuickStart MongoDB With Docker
Im gonna share how to get mongoDB up and running on your machine super quick with docker. First if you want to learn a bit more about mongo, you can go to their site and start devouring all their FREE courses here. I was using mongo with docker for quite some time, but it was with custom dockerfiles and docker-compose. I had one super quick feature I wanted to show a friend on mongo. But who has the energy to create a dockerfile or docker-compose file just to show something quick. There are few options I got (I’m sure there are more) :
running on the spot
docker run --rm -v $(PWD):/var/data -p 27017:27017 -it mongo:3.4 bash
The above will start a mongo container and will get you inside to the container with bash access. Docker is
not running yet. But now as you are inside the container you can easily interact with mongo.
mongod --fork --logpath /var/log/mongod.log
This will start mongo and go to the background so you could continue interacting with the container.
mongo
now you are inside the mongo shell and you can interact with databases, collections etc. To quickly create a new db and collection:
use sample_db
# now you have a new DB name "sample_db"
db.books.save({title: "some book"})
# now you have a new collection named "books" with one doc
** when you exit the container, it will get removed.
Running mongo container on the background of your computer
docker run --rm -d -v $(PWD):/var/data -p 27017:27017 -it --name tzmong mongo:3.4
This command will start a new docker container with mongo already running. The container name will be “tzmong”. Now you can easily access it with:
docker exec -it tzmong mongo
And now you are inside mongo shell again as before and you create dbs, collections etc. Now if you exit the container, the container will still be alive and running. If you would like to stop it, run:
docker stop tzmong