This article describes in detail how to run Mongodb in docker. I am using wsl ubuntu 20.04 as my operating system.
Install docker
(If you already have docker installed, you can skip this step…)
For ubuntu, you can refer to this tutorial: Install Docker Engine on Ubuntu.
Check the version of docker.
Download and run the mongo image
-
Download the mongo image from docker hub
1
sudo docker pull mongo
-
Make sure the mongo image is installed
-
Building a docker container
Build the container with the downloaded
mongo
image and open port 27017 so that we can access the running mongo database service through the local port 27017,--name
indicates the name of the container to be started.1
$ sudo docker run -p 27017:27017 --name mongodb -d mongo
After starting mongodb, the local machine can connect to
localhost:27017
to access the database using a database visualization client such as studio 3T.View the running docker container.
You can see that the mongodb container is running.
Stop the mongo container from running.
Looking at all containers, including those that have not stopped running, you can see that
STATUS
isexited
.Restart the container.
-
Using volume to persist data
Although mongodb is successfully started, the data inside the docker container will disappear every time the container is stopped. You can save the data by using volume so that the data can be restored and not lost after restarting the container next time.
With the
-v
command, you can create and associate a volume, where the volume name ismongo_volume
and the data storage location is/data/db/mongo
.View all volumes.
1 2 3 4 5 6 7 8 9
$ sudo docker volume ls DRIVER VOLUME NAME local 9cf22727a49818b76240fcfd16f0f017a46075974d84cca7b680d03022b1e605 local 58ee5403f72d36bc066757f3a4dc25867046d02acc7e6e69b52bfa530cbabb68 local 24553a91d0eafd60a73f23a65c0f463cb61cbf557ea64ab43d5b784d8a9622d9 local b8783d382ad0f423ec3064d94401a968ab08f1c766a71f05cdaa17e5e384efc9 local bffb4d18d9398a92711c3b121c327884e2b2f12ec175dbbb0d7611f526f6747c local d38c59edc35c306d7c3be775443b13d2dd7b925d56ad1c72ad3267dfb1b05842 local mongo_volume