Test your Docker images

Do you build Docker images regularly? You certainly know that just because your image was built without errors, it doesn’t mean it works as you expect. Building a Docker image, like any code, must be verified and validated. As your code, you can write tests that will check your images.

The tool I personally use is called Container Structure Test. Developed by Google, it allows you to write unit tests for your Docker images. Written in Go, it’s available as a binary compatible with most operating systems.

With Container Structure Test, you will:

  • Run commands inside the container and verify the output or any errors produced,
  • Test file existence,
  • Check file contents (including its associated metadata),
  • Verify the configuration of the container itself.

Once downloaded, setting up tests is done by writing rules in a YAML file. Here’s an example configuration I use to test the construction of Docker images running PHP projects:

schemaVersion: "2.0.0"

# Vérification de la présence de certaines variables d'environnement
globalEnvVars:
    - key: GITHUB_TOKEN
      value: github-token

commandTests:
    - name: "Symfony CLI installed"
      command: "which"
      args: ["symfony"]
      exitCode: 0
    - name: "Check PHP extensions"
      command: "php"
      args: ["-m"]
      expectedOutput:
          - "amqp"
          # ...


fileExistenceTests:
- name: 'Configuration PHP'
  path: 'etc/php/8.3/php.ini'
  shouldExist: false

fileContentTests:
- name: 'Linux Version'
  path: '/etc/os-release'
  expectedContents: ["VERSION_ID=3.14.2","NAME=\"Alpine Linux\""]

When the setup is complete, you just need this command:

container-structure-test test --image my-registry.jdecool.fr/php:8.3 --config php-tests.yaml

=======================================
====== Test file: php-tests.yaml ======
=======================================
=== RUN: Command Test: Symfony CLI installed
--- PASS
duration: 306.265278ms
stdout: [...]

=== RUN: Command Test: Check PHP extensions
--- PASS
duration: 303.302806ms
stdout: [...]

=== RUN: Command Test: Configuration PHP
--- PASS
duration: 276.503651ms
stdout: [...]

=== RUN: Command Test: Linux Version
duration: 276.503651ms
stdout: [...]

=======================================
=============== RESULTS ===============
=======================================
Passes:      4
Failures:    0
Duration:    789.707605ms
Total tests: 4

PASS