Docker Compose Containerized Testing
March 24, 2022
Web applications generally are composed of multiple components such as the frontend, backend and database among other things. Docker compose is great spinning up all the required components at once (using containers), so it follows you can do the same for testing as well!
Take a scenario where you are testing your backend api. This api may depend on a database. To test this, we can have a compose file with 3 containers. The first container would spin up the backend container (can build it or use existing image). The second container would spin up the database (could have db initialization scripts, not shown below.). The final container would have the e2e testing code to execute against the backend.
To model this, we could create a docker compose file that looks like so.
Example compose file
version: "3.7"services:backend:build: # build docker image from ../sample-backend/ (context) using Dockerfile in that folder.context: ../sample-backend/dockerfile: Dockerfileenvironment:- key=value- key2=value2network_mode: "host"depends_on:- dbdb:image: postgres:14.1environment:- POSTGRES_DB=<dbname>- POSTGRES_PASSWORD=<pw>ports:- 5432:5432tests:container_name: testsbuild: # The idea is to build a docker image that copies test code and executes it against local backend. Can inherit from a base image with the desired language (in this case maven).context: .dockerfile: tests/Dockerfilehealthcheck:start_period: 20stest: "exit 0" # any command to specify container is readydepends_on:- backendcommand: mvn clean test -Dcucumber.options="--tags @test"
To execute run: docker-compose -f docker-compose.yml up --force-recreate --build --exit-code-from test
Breaking down run command
-f docker-compose.yml
: This decides which docker-compose file to use, can be omitted and it will default to looking for docker-compose.yml in current directory.--force-recreate --build
: force-recreate makes sure the docker images are recreated (no cache or anything). Build - build the docker images from docker file before running.--exit-code-from test
: This specifies to exit when the test container exits. Since this compose file is meant for containerized testing, we want things to shut down after the tests container has finished executing and returns.
More Reading:
- Docker compose: https://docs.docker.com/compose/
- Docker compose up: https://docs.docker.com/engine/reference/commandline/compose_up/