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.
version: '3.8' services: mongodb: image: mongo:6-jammy ports: - '27017:27017' volumes: - datadrive:/data/db restarts: always volumes: datadrive:
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
docker compose up -d
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 server
Create a user and role for MongoDB
use admin db.createUser( { user: "rootUser", pwd: "root123", roles: ["root"] } )
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.
use demo db.createUser( { user: "demoUser", pwd: "demo123", roles: [ { role: "readWrite", db: "demo" } ] } );
 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.
version: '3.8' services: mongodb: image: mongo:6-jammy ports: - '27017:27017' volumes: - datadrive:/data/db command: [--auth] restarts: always volumes: datadrive:
Now your MongoDB server authentication has been enabled successfully, you can verify this using the below command
docker exec -it mongodb bash mongosh -u rootUser -p root123

An error has occurred. This application may no longer respond until reloaded. Reload 🗙