Install MongoDB Inside Docker Container in Linux

Install MongoDB Inside Docker Container in Linux

MongoDB is a cross-platform document database. It is classified as a NoSQL database. Instead of using tables and rows as in the relational databases such as MySQL, MongoDB uses JSON-like documents. MongoDB is an open-source project available under the Server Side Public License (SSPL).

This tutorial explains how to install MongoDB inside a Docker container in the Linux. Commands have been tested on Ubuntu.

Prepare environment

Make sure you have installed Docker in your system. If you are using Ubuntu, installation instructions can be found in the post.

Install MongoDB

  • Host network

Run the following command to create a container for MongoDB that uses host network:

docker run -d --name=mongodb --restart=always --network=host \
    -v /opt/mongodb/db:/data/db \
  • User-defined bridge network

User-defined bridge network can be used for listening on different port. By default, MongoDB service is listening on port 27017. It can be changed with -p option.

docker network create app-net
docker run -d --name=mongodb --restart=always --network=app-net \
    -p 8080:27017 \
    -v /opt/mongodb/db:/data/db \

Note: don't forget to change admin password.

Testing MongoDB

Run the following command to open the MongoDB Shell (mongosh) and enter password:

docker exec -it mongodb mongosh -u admin --eval "show dbs"

The command displays all databases on MongoDB server:

Current Mongosh Log ID: 63831f5e6c16ad60ccf672f1

admin   100.00 KiB
config   12.00 KiB
local    40.00 KiB

Uninstall MongoDB

To completely remove MongoDB, remove its container and associated volume:

docker rm --force --volumes mongodb

Remove MongoDB image:

docker rmi mongo

You can also remove MongoDB data:

sudo rm -rf /opt/mongodb

If a user-defined bridge network was created, you can delete it as follows:

docker network rm app-net

Leave a Comment

Cancel reply

Your email address will not be published.