I'm writing a very simple bash script to quickly check that my container still builds and starts correctly and that the app inside responds to requests.
Sometimes docker run
fails, e.g. because the port I'm trying to bind the container to is already allocated. But when this happens docker run
's exit code is still 0 so I can't use the exit code. How can I check programmatically that the container got started correctly?
The solutions I'm considering are:
- parse the output for errors
docker ps
to see if the container is running
but these both seem a little overkill and ugly. Am I missing a better way to check whether docker run
succeeded?
As suggested by Abel Muiño in comments, this may have been fixed in more recent Docker versions (I'm currently running 0.9.1).
But, if you're temporarily stuck like me with an older version, I did find a decent workaround to check if the container started by using
docker inspect
.docker inspect
returns a JSON object with a lot of info about the container, and in particular whether the container is currently running or not. The-f
flag lets you easily extract the bits needed:or
will return
true
orfalse
.Note that you probably want to
sleep 1
(or more) between starting the container and checking if it is up. If there's something wrong with your setup it's possible that it would appear as 'running' for a very short time before actually exiting.To avoid parsing anything, you could use docker top, which returns 1 if the container is not running:
We could use
docker exec $id true 2>/dev/null || echo not running
.This command does not write to stdout, as "docker top" does. It writes to stderr when the container is not running, the same message as "docker top".