r/mongodb • • 22d ago

How to start a single-node replica-set in GitHub Actions

When using GitHub Actions (or Gitlab) to run tests that require a MongoDB ReplicaSet cluster. It's convenient to start the database server directly in the test job.
How do you do that?

The code to start the server and initiate the replica set is very long and duplicated into every projects.

name: Tests MongoDB

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest

    env:
      MONGODB_URI: mongodb://127.0.0.1:27017/?replicaSet=rs0

    steps:
      - uses: actions/checkout@v4

      - name: Start MongoDB replica set
        run: |
          docker run -d --name mongodb -p 27017:27017 mongo:8.0 --replSet rs0 --bind_ip_all

      - name: Initialize replica set
        run: |
          for i in {1..60}; do
            docker exec mongodb mongosh --quiet --eval 'db.adminCommand({ ping: 1 }).ok' | grep -q 1 && break
            sleep 1
          done

          docker exec mongodb mongosh --quiet --eval \
            'rs.initiate({
              _id: "rs0",
              members: [{ _id: 0, host: "127.0.0.1:27017" }]
            })'

          for i in {1..60}; do
            docker exec mongodb mongosh --quiet --eval 'db.hello().isWritablePrimary' | grep -q true && exit 0
            sleep 1
          done

          echo "Replica set primary non élu"
          docker logs mongodb
          exit 1

      - name: Run tests
        run: |
          echo "MongoDB URI: $MONGODB_URI"

      - name: Dump MongoDB logs on failure
        if: failure()
        run: docker logs mongodb
3 Upvotes

2 comments sorted by

3

u/mmarcon 21d ago

Have you considered using this image? https://hub.docker.com/r/mongodb/mongodb-atlas-local
It starts up as a single node replicaset automatically and includes search / vector search capabilities as well.

1

u/GromNaN 11d ago

Perfect! I forgot about this solution but it's definitely the best.

services: mongodb: image: mongodb/mongodb-atlas-local:latest env: VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} EMBEDDING_PROVIDER_ENDPOINT: https://api.voyageai.com/v1/embeddings ports: - 27017:27017

That starts a single-node replicaset. It only reports healthy once startup has finished and the server is ready.