In this example, I run a MongoDB container using named volumes and bind mounts.
Procedure:
To run a new MongoDB container, execute the following command from the CLI:
docker run --rm --name mongo-dev -v mongo-dev-db:/data/db -d mongo
CLI Command | Description |
---|---|
--rm | remove container when stopped |
--name mongo-dev | give container a custom name |
-v mongo-dev-db/data/db | map the container volume 'data/db' to a custom name 'mongo-dev-db' |
-d mongo | run mongo container as a daemon in the background |
cd
mkdir -p mongodb/data/db
docker run --rm --name mongo-dev -v ~/mongodb/data/db:/data/db -d mongo
CLI Command | Description |
---|---|
--rm | remove container when stopped |
--name mongo-dev | give container a custom name |
-v ~/mongodb/data/db/data/db | map the container volume 'data/db' to a bind mount '~/mongodb/data/db' |
-d mongo | run mongo container as a daemon in the background |
There are 2 steps to accessing the MongoDB shell.
-
Firstly, access the MongoDB container shell by executing the following command:
docker exec -it mongo-dev bash
This will open an interactive shell (bash) on the MongoDB container.
-
Secondly, once inside the container shell, access the MongoDB shell by executing the following command:
mongo localhost
Once connected to MongoDB shell, run the following command to show a list of databases:
show dbs
Create a new database and collection
use test
db.messages.insert({"message": "Hello World!"})
db.messages.find()