Create a mongodb container with docker and connect with mongodb compass
The no-nonsense two minute guide to setting up and connecting a mongodb instance inside a docker container
This a very quick walkthrough of spinning up a mongodb server inside a docker container and connecting with it through the mongodb compass gui.
Why would you wanna do this?
You wanna get rid of MongoDB Atlas
You want a FREE solution
You want autonomy over how to manage and deploy your server
Pre-requisites:
Basic understanding of how to run a docker image
Basic understanding of what MongoDB is.
For when you just need to spin up a quick MongoDB server don't want to spin up a MongoDB Atlas instance (Ugh, sign up, login, spin up a server and wait for it to get ready. It's a hassle)
Docker allows to quickly spin up a server ad-hoc without needing to sign up on any service and pay for any service. All you need is to have docker installed on your machine and internet connection (to download the mongodb image from the doker registry).
How to run docker inside a container
Once you have both, here's how you set it up. Firstly, open up the terminal and type the following command
docker run --name mongodbcontainer -p 27017:27017 -e MONGO_INITDB_ROOT_USERNAME=mongodbrootusername -e MONGO_INITDB_ROOT_PASSWORD=mongodbrootpassword -d mongo
In the above command,
1. "-p" denotes port. Left side denotes the port on YOUR COMPUTER and right side denotes port to listen to INSIDE DOCKER CONTAINER
2. "-e" denotes environment variables
3. "-d" denotes daemon mode, ie the process will run in the background and not take up your terminal
4. "--name" denotes the name that you can assign to the container
Connect MongoDB inside container to your app
Once you've run this command, it will spin up a mongodb server inside a docker container. To connect to that container from a (for example, nodejs) app, here's the connection string you must enter.
mongodb://mongodbrootusername:mongodbrootpassword@localhost:27017/?retryWrites=true&w=majority
And that's that. You are now conneted to an instance of MongoDB running inside a container on your machine.