Skip to content
Latchkey

How to Spin Up MongoDB for Tests in GitHub Actions

A MongoDB service container exposes a real database on localhost:27017; a mongosh ping probe confirms the server is accepting connections.

Declare mongodb under services: with the official mongo image, map port 27017, and probe readiness by running a db.adminCommand("ping") through mongosh.

Steps

  • Add services.mongodb with image: mongo:7.
  • Map ports: [27017:27017].
  • Health-check by running db.adminCommand({ ping: 1 }) through mongosh.
  • Connect with mongodb://localhost:27017.

Workflow

.github/workflows/ci.yml
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      mongodb:
        image: mongo:7
        ports:
          - 27017:27017
        options: >-
          --health-cmd "mongosh --quiet --eval 'db.adminCommand({ ping: 1 })'"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
    env:
      MONGO_URL: mongodb://localhost:27017/app_test
    steps:
      - uses: actions/checkout@v4
      - run: npm ci && npm test

Gotchas

  • The mongo:7 image bundles mongosh; older images shipped the legacy mongo shell, so adjust the health command per tag.
  • Single-node replica-set features (transactions, change streams) need --replSet plus rs.initiate(); a plain service container is standalone.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →