Using MongoDB on Docker
Installing MongoDB is difficult and time-consuming and requires many configuration changes. All this process can be made easy by using MongoDB over Docker.
Here is a short and simple tutorial that I wrote for myself and sharing here. I’m using Kali Linux 20.04. It should be similar for all other OS.
Depending on how docker is configured on your system you might need to use
sudo
before all the docker commands
Step 1: Pull docker image of MongoDB
docker pull mongo
The MongoDB image will be downloaded.
Check the list of docker images
docker images
Step 2: Create a container
docker run -d -p 27017:27017 -v /data/db:/data/db --name mongo_cont mongo
In /data/db:/data/db
, the first part in the path where the data is stored on your system(change this if required). The 2nd part is the path where the data is saved by MongoDB inside the container.
The container mongo_cont should be running. Check the list of containers. Make sure port 27017 is not occupied already.
docker ps -a
Step 3: Get into the container to use mongo shell
docker exec -it <CONTAINER ID> bash
Now you are inside the container. Open mongo shell in the container using:-
mongo
- Stopping the container
docker stop <CONTAINER ID>
- Starting the container again after stopping and using it again
docker start <CONTAINER ID>
docker exec -it <CONTAINER ID> bash
Some important points:-
- All the containers have the same databases
- Stopping the container doesn’t delete the database data
- Restarting the system doesn’t delete the database data
- Deleting the container doesn’t delete the database data. When a new container is created the previous data is present in it.
Originally published at https://blog.subhrapaladhi.com.