Martin Thoma
Martin Thoma

Reputation: 136605

How can I write a unit test for a Docker container with Flask web service?

I have a Flask web service inside a Docker container.

What I currently do:

$ docker run -p 8080:8080 --rm my_image serve.py
$ curl -d '{"foo": "bar", "foo2": "bar2"}' -H "Content-Type: application/json" -v http://localhost:8080/ping

If that returns status code 200, it's fine.

Can I do this automatically? Preferably with tox?

Upvotes: 0

Views: 1039

Answers (1)

yamenk
yamenk

Reputation: 51826

Docker HealthChecks might useful. A health check is a command that is executed regularly to determine if a container is healthy.

Health checks usually consist of curling an http endpoint and checking the return code.

You can define a health check inside the Dockerfile as such:

HEALTHCHECK --interval=5m --timeout=3s \
 CMD curl -d '{"foo": "bar", "foo2": "bar2"}' -H "Content-Type: application/json" -v http://localhost:8080/ping || exit 1

Or when running the container as such:

docker run --health-cmd='curl -d '{"foo": "bar", "foo2": "bar2"}' -H "Content-Type: application/json" -v http://localhost:8080/ping || exit 1' --health-interval=5m  --health-timeout=3s ...

The container health will then show next to the status when running docker container ls

Upvotes: 1

Related Questions