How to run MongoDB using docker compose with authentication
Posted on February 05, 2024
•
1 min read
MongoDB is a non-relational document database with scalability and flexibility. Here we will explain how to run the MongoDB server using the docker-compose with authentication. Running MongoDB using the docker commands is quite complicated because needs to remember all the docker commands and parameters. Docker compose file makes it easier to run the MongoDB server using the compose file.
In this example, we are using an office MongoDB image with the tag
6-jammy
. In this, it runs MongoDB uses a docker-managed volume so that data for the database is kept even if the container restarts.Now run the docker using the below command
Enable MongoDB authentication
By default, there is no authentication in MongoDB. It means connecting the MongoDB db server without any authentication. After running the container to inspect the docker container using
docker exec -it mongodb bash
Then run the
mongosh
command to connect the MongoDB serverCreate a user and role for MongoDB
Using the above command we create the admin user with a username
rootuser
and password root123
in the admin database. In the same way, you can create the user and role for your other databases like the below one. Now we are ready to enable the authentication on the MongoDB server. To enable the authentication
--auth
flag add as a command in the docker-compose file. After that recreate the docker container using docker-compose up -d
the command again.Now your MongoDB server authentication has been enabled successfully, you can verify this using the below command