79221018

Date: 2024-11-24 20:31:21
Score: 0.5
Natty:
Report link

I think some stuff changed since the answers for mongo 6 did not work for me, using mongo 8. So I made slight tweaks (here's a GitHub repository).

openssl rand -base64 756 > ./init/mongo/mongo-keyfile
chmod 400 ./init/mongo/mongo-keyfile
name: mongo-stack

services:
  mongo:
    image: mongo:8.0
    restart: unless-stopped
    command: ["--replSet", "rs0", "--keyFile", "/etc/mongo-keyfile"]
    container_name: starter-mongo
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
    volumes:
      - mongo-vol:/data/db
      - ./init/mongo/mongo-keyfile:/etc/mongo-keyfile:ro
    networks:
      - mongo-net
    ports:
      - 27017:27017
    healthcheck:
      test: mongosh --host localhost:27017 --eval 'db.adminCommand("ping")' || exit 1
      interval: 5s
      timeout: 30s
      start_period: 0s
      start_interval: 1s
      retries: 30

  mongo-init-replica:
    image: mongo:8.0
    container_name: mongo-init-replica
    depends_on:
      - mongo
    volumes:
      - ./init/mongo/init-replica.sh:/docker-entrypoint-initdb.d/init-replica.sh:ro
    entrypoint: ["/docker-entrypoint-initdb.d/init-replica.sh"]
    networks:
      - mongo-net

volumes:
  mongo-vol:
    driver: local

networks:
  mongo-net:
    name: starter-mongo-net
    driver: bridge
#!/bin/bash

echo ====================================================
echo ============= Initializing Replica Set =============
echo ====================================================

# Loop until MongoDB is ready to accept connections
until mongosh --host mongo:27017 --eval 'quit(0)' &>/dev/null; do
    echo "Waiting for mongod to start..."
    sleep 5
done

echo "MongoDB started. Initiating Replica Set..."

# Connect to the MongoDB service and initiate the replica set
mongosh --host mongo:27017 -u root -p example --authenticationDatabase admin <<EOF
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "localhost:27017" }
  ]
})
EOF

echo ====================================================
echo ============= Replica Set initialized ==============
echo ====================================================

Please note that I tried to run the entry point file directly from the mongo service but it simply refused to initiate the replica set for whatever reason. It had to be done from a separate container.

Reasons:
  • Blacklisted phrase (1): did not work
  • Contains signature (1):
  • Long answer (-1):
  • Has code block (-0.5):
Posted by: usersina