6

There's already a similar question at What happens to a Docker Container when HEALTHCHECK fails, but the secondary point about || exit 1 was not the main focus of the question (and it hasn't been answered directly).

The Dockerfile reference contains the following example:

HEALTHCHECK
 --interval=5m --timeout=3s \
  CMD curl -f http://localhost/ || exit 1

I have seen several other examples of healthcheck instructions ending in || exit 1 around the Internet. Even when the only two possible exit codes of the original command are 0 and 1.

What's the point of || exit 1?

Wont curl -f exit on its own with error code 22? Does Docker fail to recognise error codes other than 1?

Anthony Accioly
  • 21,918
  • 9
  • 70
  • 118
  • 2
    No, I don't think you don't need it. You could also try it out, which may be quicker than waiting for an answer. – The Fool May 31 '22 at 21:37
  • I've tried it already and the containers does eventually become healthy. I'm just asking because it may be there to deal with some kind of corner case. – Anthony Accioly May 31 '22 at 21:38
  • 3
    In the docs is written that possible value are only 0,1 and 2. So I guess it is more clean, https://docs.docker.com/engine/reference/builder/#healthcheck. – The Fool May 31 '22 at 21:41

1 Answers1

8

Even when the only two possible exit codes of the original command are 0 and 1.

That's a big assumption that isn't being made by those writing the commands with || exit 1. If a command exits with a 2 or any other code except for a 0 or 1, that's undefined behavior. Presumably docker is reserving other exit codes for any additional behavior they might come up with in the future.

Specifically with curl, it can exit with a lot of other values which have a meaning for curl but would be undefined behavior for the healthcheck.

BMitch
  • 231,797
  • 42
  • 475
  • 450
  • Fair enough, so when someone is sure that the original command only returns 0 or 1, then the `|| exit` part is redundant right? I'm just double checking if there's no other possibility that would lead someone to use `|| exit 1` other than fear of unknown exit codes. I'm about to remove `|| exit 1` from a bunch of private docker / docker-compose.yml files (they are using handwritten healthcheck scripts that will only ever return 0 or 1). – Anthony Accioly May 31 '22 at 21:49
  • 1
    You're shifting the responsibility to the shell script. If you own the script and can ensure that it will never have another return code (e.g. no one ever includes something like a `set -e` in the script), then yes, it's redundant. – BMitch May 31 '22 at 22:57