Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 views
in Technique[技术] by (71.8m points)

bash - How to detect if docker run succeeded programmatically?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

docker inspect -f {{.State.Running}} $CONTAINER_ID

or

docker inspect -f "{{.State.Running}}" $CONTAINER_ID

will return true or false.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...