How-to
If you want to use the healthcheck feature for a container.
You can inspect a container with docker inspect $CONTAINER_NAME
.
The response is an array with one JSON object:
[
{
"Id": "CONTAINER_ID",
"Created": "2021-11-09T21:18:05.552662745Z",
"Path": "/start.py",
"Args": [],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 12872,
"ExitCode": 0,
"Error": "",
"StartedAt": "2021-11-09T21:18:08.697693764Z",
"FinishedAt": "0001-01-01T00:00:00Z",
"Health": {
"Status": "healthy",
"FailingStreak": 0,
"Log": [
{
"Start": "2021-11-10T18:51:32.122181664Z",
"End": "2021-11-10T18:51:32.304082149Z",
"ExitCode": 0,
"Output": "OK"
}
]
}
},
"Image": "IMAGE_SH"
"HostConfig": {
...
},
"GraphDriver": {
...
},
"Mounts": [
...
],
"Config": {
"Hostname": "hostname",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts": {
"8008/tcp": {},
"8009/tcp": {},
"8448/tcp": {}
},
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
...
],
"Cmd": null,
"Healthcheck": {
"Test": [
"CMD-SHELL",
"curl -fSs http://localhost:8008/health || exit 1"
],
"Interval": 60000000000,
"Timeout": 5000000000
},
"Image": "IMAGE_NAME",
"Volumes": {
"/data": {}
},
"WorkingDir": "",
"Entrypoint": [
"/start.py"
],
"OnBuild": null,
"Labels": {
...
}
},
"NetworkSettings": {
...
}
}
]
If you take a look at the object, you will find the healthcheck cmd.
curl -fSs http://localhost:8008/health || exit 1
Check the curl docs, how the options return a nice result. Now what you can do, you can search for it using grep:
docker inspect $CONTAINER_NAME | grep "healthy"
"Status": "healthy",
The problem in this case is, you want a boolean result. So you have different option, you can handle this case with option -o of the grep search:
docker inspect docker_synapse_1 | grep -o "healthy"
"healthy"
Okay cool, let’s check the exit code. echo $?
will return 0, so know you can use this pipe in a shell script and handle if conditions.
As you may know, we are not the only one with this problem. So Docker provides a convenient solution.
Docker inspect provides the option —format, which allows us to ask for a specified JSON structure. It can do more, but for our case it is enough.
docker inspect --format {% raw %}'{{.State.Health.Status }}{% endraw %}' $CONTAINER_NAME
The command above will return healthy.
if you want the double quotes, you can add json after the curly brackets, like {% raw %}{{json .State...}}{% endraw %}
.
So there you have it, you can now check against this string using grep or just [[ $? != "healthy"]]
.
Advantages:
- No pipe required.
- Returning the exact value of the object key.
- Just Docker, no strings attached.