Deploy MongoDB on Docker

Deploy MongoDB on Docker
Photo by ammiel jr / Unsplash

For development and testing purpose, we have been using MongoDB container image on docker.

For load testing, it simplifies as we can spawn new database with seed data easily. Follow this article to deploy MongoDB instance on a docker container

Prerequisites


  • A user with Administrator privileges (in Mac, sudo privileges)
  • Docker desktop installed. To install docker desktop, follow the links - window - mac

Deploy MongoDB


To start a mongo server instance, run the following command

docker run -d -p 27017:27017 --name mongodb mongo 
  • -d - starts the container as a background process
  • -p - binds the container port to the host port. 27017 is the default port for mongo server instance
  • --name - container name. In our case, we used mongodb as container name

docker run command will automatically pull image from docker hub, if it is not available locally, will create container and starts it.

To check container status, use the following command

docker ps

To check mongo server instance logs, use the following command

docker logs mongodb

To access mongo server instance, use the command to open interactive terminal

docker exec --it mongodb bash

and start the mongodb shell by typing mongo in the interactive terminal

To exit the mongo shell, type exit and then type exit again to leave the interactive shell

Start and Stop container


To stop mongodb container, you can use docker stop command as below

docker stop mongodb

To start the mongodb container, use docker start command as below

docker start mongodb

For us, using mongodb on docker helped to improve our development and testing process efficiently by 2x.

Happy coding :-)