TExcelTAD
Home › Docker › HEALTHCHECK and LABEL

HEALTHCHECK and LABEL

A container can be running and still be useless: the process is alive but stuck, out of database connections, or still warming up. HEALTHCHECK lets Docker test the app from the inside and report healthy or unhealthy. LABEL attaches metadata (who built the image, from which commit, under which licence) that tools can query.

HEALTHCHECK

dockerfile
FROM python:3.12-slim
# ... install app ...
HEALTHCHECK --interval=30s --timeout=3s --start-period=20s --retries=3 \
  CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" || exit 1
CMD ["gunicorn", "-b", "0.0.0.0:8000", "shop.wsgi"]
Option Default Meaning
--interval 30s time between checks
--timeout 30s a check that takes longer counts as failed
--start-period 0s grace period after start: failures do not count yet, but the first success marks the container healthy
--retries 3 consecutive failures needed to become unhealthy

The check command's exit code decides the result: 0 = success, 1 = failure. That is why the example ends with || exit 1, which turns any other non-zero code into 1. HEALTHCHECK NONE disables a check inherited from the base image.

The health status starts as starting and moves according to these rules. The model replays a series of check results:

python · try it yourself
def health(results, interval=30, start_period=20, retries=3):
    status, failures = "starting", 0
    for i, ok in enumerate(results, start=1):
        t = i * interval - 20          # checks at 10s, 40s, 70s, ...
        in_grace = t <= start_period
        if ok:
            status, failures = "healthy", 0
        elif in_grace and status == "starting":
            pass                       # failures during start-period are not counted
        else:
            failures += 1
            if failures >= retries:
                status = "unhealthy"
        print(f"t={t:>3}s check {'ok  ' if ok else 'FAIL'} failures={failures} -> {status}")
    return status

print("final:", health([False, True, True, False, False, True, False, False, False]))
t= 10s check FAIL failures=0 -> starting
t= 40s check ok   failures=0 -> healthy
t= 70s check ok   failures=0 -> healthy
t=100s check FAIL failures=1 -> healthy
t=130s check FAIL failures=2 -> healthy
t=160s check ok   failures=0 -> healthy
t=190s check FAIL failures=1 -> healthy
t=220s check FAIL failures=2 -> healthy
t=250s check FAIL failures=3 -> unhealthy
final: unhealthy

A single failure did not flip the status; three in a row did. A successful check resets the counter.

Look at the status with:

bash
docker ps
docker inspect --format '{{json .State.Health}}' shop

Sample output:

text
CONTAINER ID   IMAGE      STATUS                    NAMES
8b1f0c2d3e4a   shop:1.4   Up 2 minutes (healthy)    shop

{"Status":"healthy","FailingStreak":0,"Log":[{"Start":"...","ExitCode":0,"Output":""}]}

Note: plain Docker only reports health; it does not restart an unhealthy container. Compose uses health for depends_on: condition: service_healthy, Swarm replaces unhealthy tasks, and Kubernetes ignores HEALTHCHECK in favour of its own liveness and readiness probes.

Keep checks cheap and local: hit a lightweight /health endpoint, don't run a full test suite, and make sure the tool you call (curl, wget, python) actually exists in the image. Slim images often lack curl.

LABEL

dockerfile
LABEL org.opencontainers.image.title="shop-api" \
      org.opencontainers.image.version="1.4.0" \
      org.opencontainers.image.source="https://github.com/acme/shop" \
      org.opencontainers.image.revision="3f1c9a0" \
      org.opencontainers.image.licenses="MIT" \
      com.acme.team="payments"

Labels are key-value strings stored in the image config. They add no layer and no size. The org.opencontainers.image.* keys are the standard OCI annotation names that registries and scanners understand; for your own keys, use a reverse-DNS prefix (com.acme.) to avoid collisions.

Labels are inherited from the base image, and a later label with the same key overrides the earlier one. You can filter by label:

bash
docker image ls --filter label=com.acme.team=payments
docker inspect --format '{{ index .Config.Labels "org.opencontainers.image.version" }}' shop:1.4

The model below merges inherited labels and implements --filter label=...:

python · try it yourself
base_labels = {"maintainer": "python-docker", "org.opencontainers.image.licenses": "PSF-2.0"}

images = {
    "shop-api:1.4": {"org.opencontainers.image.licenses": "MIT", "com.acme.team": "payments",
                      "org.opencontainers.image.version": "1.4.0"},
    "billing:2.0":  {"com.acme.team": "payments", "org.opencontainers.image.version": "2.0.0"},
    "blog:0.9":     {"com.acme.team": "content"},
}

def effective(own):
    labels = dict(base_labels)
    labels.update(own)                 # later LABELs win
    return labels

def filter_images(expr):
    key, _, value = expr.partition("=")
    for name, own in images.items():
        labels = effective(own)
        if key in labels and (not value or labels[key] == value):
            yield name

print(effective(images["shop-api:1.4"]))
print("team=payments:", list(filter_images("com.acme.team=payments")))
print("has a version:", list(filter_images("org.opencontainers.image.version")))
{'maintainer': 'python-docker', 'org.opencontainers.image.licenses': 'MIT', 'com.acme.team': 'payments', 'org.opencontainers.image.version': '1.4.0'}
team=payments: ['shop-api:1.4', 'billing:2.0']
has a version: ['shop-api:1.4', 'billing:2.0']

Tip: set the version and revision labels from CI with build args (--build-arg VERSION=$TAG), so every image can be traced back to the commit that produced it.

Test yourself

With --retries=3, when does a container become unhealthy?

  1. After the first failed check
  2. After 3 consecutive failed checks
  3. After 3 failures in total, even if checks pass in between
  4. Never, Docker only shows starting

What does plain docker run do when a container becomes unhealthy?

  1. Restarts it automatically
  2. Deletes it
  3. Only reports the status; something else must react
  4. Rolls back to the previous image

How much does a LABEL instruction add to the image size?

  1. One full layer
  2. Nothing; labels live in the image config
  3. 1 MB per label
  4. It depends on the base image