Skip to main content

Overview

In this guide, you’ll configure a non-production MongoDB instance as a service container in your GitHub Actions workflow. This ensures your unit tests run against an isolated database and keeps production data safe.
Never point your test suite at a production database. Service containers provide complete isolation for reliable, repeatable testing.

Existing Workflow: unit-testing Job

Here’s the current setup that uses a production MongoDB URI:

What Are Service Containers?

Service containers run alongside your job on the same virtual network. They’re ideal for databases, caches, message brokers, or any external service your tests require.
The image shows a GitHub documentation page about service containers, explaining their use in connecting databases, web services, and other tools in workflows. The page includes navigation links and a note on using Docker containers with GitHub Actions.
Service containers are automatically networked with your job runner. You can refer to them by their service name (e.g., mongo-db) or localhost with exposed ports.

Pre-built MongoDB Image on Docker Hub

We’ll use a custom MongoDB image tagged non-prod:
The image shows a Docker Hub page displaying details of a Docker image named "siddharth67/mongo-db:non-prod," including its digest, OS/architecture, compressed size, and image layers.
  • Image name: siddharth67/mongo-db:non-prod
  • Exposes port 27017

Updated Workflow with MongoDB Service

Service Definition

Full Workflow YAML

Workflow Execution and Logs

When triggered, GitHub Actions creates a private Docker network, pulls the MongoDB image, and starts the service container:
The image shows a GitHub Actions interface running a workflow for unit testing on Ubuntu, displaying job setup and log details.
Once healthy, the test steps connect using:
The image shows a GitHub Actions workflow interface with a "modified mongo uri" workflow in progress, displaying unit testing, code coverage, and containerization steps.

Next Steps

  • Extend this pattern to other tools: PostgreSQL, Redis, Elasticsearch, and more.
  • Parameterize image tags or use official Docker Hub images for broader compatibility.
  • Integrate code coverage or linting services in additional jobs.

Watch Video