Installing MongoDB with Docker

Installing MongoDB with Docker

Downloading the MongoDB Docker image

Run the following command to download the MongoDB Docker image. If you do not specify a version in the tag, the latest version is downloaded.

docker pull mongo

The result is as follows.

% docker pull mongo
Using default tag: latest
latest: Pulling from library/mongo
ea362f368469: Pull complete
ecab26900ceb: Pull complete
1847fcb70562: Pull complete
a7de23811c0d: Pull complete
29dd51833fb9: Pull complete
5eccd2be8afb: Pull complete
cd8a8cd6879f: Pull complete
e6ca3abc397d: Pull complete
7481c3682d3c: Pull complete
af377cb9eb7d: Pull complete
Digest: sha256:6743836d42756b2ae50549b2eb4585c688fce81a243cedd152b56266c2fb3d17
Status: Downloaded newer image for mongo:latest
docker.io/library/mongo:latest

To specify the MongoDB version, specify the version in the tag. You can check available MongoDB versions on Docker Hub.

Check the downloaded Docker image with the following command.

docker images

The result is as follows.

% docker images
REPOSITORY                                      TAG            IMAGE ID       CREATED         SIZE
mongo                                           latest         ee13a1eacac9   2 days ago      696MB

Creating and running a MongoDB Docker container

docker run --name my-mongodb -v ~/mongodb/db:/data/db -d -p 27017:27017 mongo

-v ~/mongodb/db:/data/db mounts the ~/mongodb/db directory on the host, meaning the local computer running the container, to the /data/db directory in the container. If you do not set up a volume this way, the stored data is deleted when the container is deleted. Once deleted, container data cannot be recovered.

% docker run --name my-mongodb -v ~/mongodb/db:/data/db -d -p 27017:27017 mongo
ade97bdb08fde4eaa72ceb0135b0a570d97b21616affb7949a0fc479fec25e0e

Starting, stopping, and restarting a MongoDB Docker container

Stop the MongoDB Docker container.

docker stop my-mongodb

Start the MongoDB Docker container.

docker start my-mongodb

Restart the MongoDB Docker container.

docker restart my-mongodb

Checking whether the MongoDB Docker container is running

Run the following command.

% docker ps -a
CONTAINER ID   IMAGE                                                  COMMAND                  CREATED          STATUS                      PORTS                                       NAMES
ade97bdb08fd   mongo                                                  "docker-entrypoint.s..."   37 seconds ago   Up 36 seconds               0.0.0.0:27017->27017/tcp                    my-mongodb

Connecting to the MongoDB Docker container

Run the following command.

docker exec -it my-mongodb bash

The result is as follows.

% docker exec -it my-mongodb bash
root@ade97bdb08fd:/#