How to set up secret authentication when installing MongoDB using Docker?
To install MongoDB on Docker with authentication enabled, you can follow these steps:
- Pull the official MongoDB image using Docker command.
docker pull mongo
- Run a MongoDB container and configure authentication settings.
docker run -d --name mongodb -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=your_password mongo
Replace your_password in this command with the password you want to set.
- Now you can connect to the MongoDB container and authenticate using the following command.
docker exec -it mongodb mongo admin -u admin -p your_password
Similarly, replace your_password with the password you have set.
- Once connected successfully, you can create additional users and assign roles, such as:
use mydatabase
db.createUser(
{
user: "myuser",
pwd: "user_password",
roles: [ { role: "readWrite", db: "mydatabase" } ]
}
)
This will create a user named myuser with the password user_password and grant them read and write permissions on the database mydatabase.
- Finally, you can exit the MongoDB Shell and restart the container to apply the new authentication settings.
exit
docker restart mongodb
By doing this, you have successfully installed MongoDB in Docker and set up authentication. Remember to modify the password and authorization settings according to your needs and security requirements.