openssl rand -base64 756 > mongo-keyfile
chmod 400 mongo-keyfile
Keyfile (mongo-keyfile): The keyfile is mounted into each container at /etc/mongo-keyfile. MongoDB uses this file to authenticate communication between replica set members.
- --keyFile: This option specifies the location of the keyfile within the container.
- --auth: This option enables authentication, requiring users to authenticate before they can connect to the MongoDB instance.
Start the Docker Containers
docker-compose up -d
Exec to mongo1 to set replica
docker exec -it mongo1 mongosh --username root --password example --authenticationDatabase admin
use admin
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "mongo1:27017" },
{ _id: 1, host: "mongo2:27017" },
{ _id: 2, host: "mongo3:27017" }
]
})
rs.status() // it should show replicaset information, including members
docker exec -it mongo1 mongosh --username root --password example --authenticationDatabase admin
use mydatabase
db.mycollection.insertOne({ name: "Alice", age: 30 })
db.mycollection.insertOne({ name: "Bob", age: 25 })
db.mycollection.insertOne({ name: "Charlie", age: 35 })
db.mycollection.find().pretty()
check data in the replica mongo2, it should show same data as the mongo1
docker exec -it mongo1 mongosh --username root --password example --authenticationDatabase admin
use mydatabase
db.mycollection.find().pretty()