Running MongoDB in docker

Contents

Select the version of the docker image

IMAGE=mongo
TAG=4.4.3-bionic

Set container name

NAME=mongodb

Pull the docker image

docker pull $IMAGE:$TAG

Configure the MongoDB instance

Contents of the .env file.

MONGO_INITDB_ROOT_USERNAME=user
MONGO_INITDB_ROOT_PASSWORD=topsecret

Set the local data directory

LOCAL_DATA_DIR=`pwd`/data

Set the network parameters

INTERFACE=127.0.0.1
PORT=27017

Run the MongoDB container

docker run -d --name $NAME --env-file .env -p $INTERFACE:$PORT:27017 \
    -v "$LOCAL_DATA_DIR:/data" $IMAGE:$TAG

Test connection

docker run --rm --link $NAME -it $IMAGE:$TAG \
        mongo --host $NAME \
        -u user \
        -p topsecret \
        --authenticationDatabase admin \
        some-db
db.getName();

Inspect the container

docker inspect $NAME

See the container logs

docker logs $NAME

Kill the container

docker kill $NAME

Remove the container

docker rm $NAME

Remove the data directory

rm -rf data

References

  1. https://hub.docker.com/_/mongo/