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.mongodbwithimage: mongo:7. - Map
ports: [27017:27017]. - Health-check by running
db.adminCommand({ ping: 1 })throughmongosh. - 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 testGotchas
- The
mongo:7image bundlesmongosh; older images shipped the legacymongoshell, so adjust the health command per tag. - Single-node replica-set features (transactions, change streams) need
--replSetplusrs.initiate(); a plain service container is standalone.
Related guides
How to Spin Up a Redis Service for Tests in GitHub ActionsRun Redis as a GitHub Actions service container with a redis-cli ping health check so caches, queues, and rat…
How to Spin Up a Postgres Service for Tests in GitHub ActionsRun a real Postgres alongside your GitHub Actions tests using a service container with a pg_isready health ch…
How to Wait for a Database to Be Ready in GitHub ActionsMake GitHub Actions wait until a database accepts connections using service health checks or a pg_isready ret…