0
0
DockerHow-ToBeginner · 4 min read

How to Test Using Docker in CI: Simple Guide

To test using docker in CI, create a Docker container that runs your tests and integrate it into your CI pipeline using a docker run command. This ensures tests run in a clean, consistent environment every time.
📐

Syntax

The basic syntax to run tests inside Docker during CI is:

  • docker build -t <image-name> . - Builds a Docker image with your test environment.
  • docker run --rm <image-name> - Runs the container and executes tests, removing the container after completion.
bash
docker build -t my-test-image .
docker run --rm my-test-image
💻

Example

This example shows a simple Dockerfile that installs Node.js and runs tests using npm test. The CI pipeline builds this image and runs tests inside the container.

dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
CMD ["npm", "test"]
💻

Example

bash
# Build the Docker image
$ docker build -t node-test .

# Run tests inside the container
$ docker run --rm node-test

> my-app@1.0.0 test /app
> jest

 PASS  test/example.test.js
  ✓ example test (5 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.234 s
Ran all test suites.
Output
> my-app@1.0.0 test /app > jest PASS test/example.test.js ✓ example test (5 ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 1.234 s Ran all test suites.
⚠️

Common Pitfalls

Common mistakes when testing with Docker in CI include:

  • Not copying test files into the Docker image, causing tests to be missing.
  • Forgetting to run npm install or dependencies inside the image.
  • Not using --rm with docker run, leaving stopped containers behind.
  • Running tests outside the container, which can cause environment differences.
dockerfile
Wrong:
FROM node:18-alpine
WORKDIR /app
COPY package.json ./
CMD ["npm", "test"]

Right:
FROM node:18-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
CMD ["npm", "test"]
📊

Quick Reference

Tips for testing with Docker in CI:

  • Always build a fresh image in CI to avoid stale dependencies.
  • Use --rm to clean up containers after tests.
  • Keep your Dockerfile simple and focused on test environment setup.
  • Use volumes only if you need to persist data between steps.

Key Takeaways

Build a Docker image that includes your test environment and code.
Run tests inside the container using docker run --rm to keep CI clean.
Copy all necessary files and install dependencies inside the Docker image.
Avoid running tests outside Docker to ensure consistent environments.
Clean up containers automatically to prevent resource waste in CI.