Secure MongoDB Cluster Using Docker Compose
Setting up a secure MongoDB cluster using Docker Compose. In this example, we’ll create a MongoDB replica set with authentication enabled. Make sure you have Docker and Docker Compose installed on your system before proceeding.
Create a directory for your MongoDB cluster setup and navigate to it:
mkdir mongodb-cluster
cd mongodb-cluster
Create a file named docker-compose.yml
and add the following configuration:
version: '3.8'
services:
mongodb-primary:
image: mongo:4.4
container_name: mongodb-primary
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: adminpass
command: mongod --replSet rs0 --bind_ip_all --auth
ports:
- "27017:27017"
networks:
- mongo-cluster-net
mongodb-secondary-1:
image: mongo:4.4
container_name: mongodb-secondary-1
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: adminpass
command: mongod --replSet rs0 --bind_ip_all --auth
networks:
- mongo-cluster-net
mongodb-secondary-2:
image: mongo:4.4
container_name: mongodb-secondary-2
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: adminpass
command: mongod --replSet rs0 --bind_ip_all --auth
networks:
- mongo-cluster-net
networks:
mongo-cluster-net:
driver: bridge
In this configuration, we’re setting up a replica set with three MongoDB nodes. Each node has authentication enabled with the admin
user having the password adminpass
.
Run the Docker Compose setup:
docker-compose up -d
Access the primary MongoDB container and initiate the replica set:
docker exec -it mongodb-primary bash
Inside the container, run the following commands to initiate the replica set (Also you can set a one time running container to do this automatically.):
mongo --username admin --password adminpass --authenticationDatabase admin
> rs.initiate({_id: "rs0", members: [{_id: 0, host: "mongodb-primary:27017"}, {_id: 1, host: "mongodb-secondary-1:27017"}, {_id: 2, host: "mongodb-secondary-2:27017"}]})
Exit the container once the replica set initialization is done:
exit
Your MongoDB cluster with authentication should now be up and running. You can connect to the primary node using a MongoDB client and the appropriate connection string.
Remember that this is a basic example to help you get started. For production environments, you should consider additional configuration, security measures, and proper network settings. Additionally, MongoDB versions and container images may change, so be sure to consult the latest documentation and adjust the configuration accordingly.