TExcelTAD
Home › Docker › Docker Best Practices

Docker Best Practices

This lesson pulls the advice from the whole course into one checklist, and then turns it into a small linter you can run against any Dockerfile.

Images

  1. Pin your base image to a specific version (python:3.12.11-slim), or a digest for full reproducibility. Never latest.
  2. Choose a small, maintained base: -slim, distroless, or Alpine when your stack supports musl.
  3. Use multi-stage builds so compilers and dev dependencies stay out of the runtime image.
  4. Order instructions for the cache: system packages → dependency manifests → install dependencies → source code.
  5. Combine and clean up in the same RUN (apt-get update && apt-get install ... && rm -rf /var/lib/apt/lists/*).
  6. Add a .dockerignore with .git, node_modules, build output, .env files.
  7. Prefer COPY over ADD, unless you need tar extraction or a checksummed URL.
  8. Run as a non-root user (USER 10001) and give files the right owner with COPY --chown.
  9. Use exec form for CMD/ENTRYPOINT so signals reach your app.
  10. Add HEALTHCHECK and OCI LABELs (version, source, revision).
  11. No secrets in images: no ARG/ENV passwords, no copied keys. Use build secrets.

Containers

  1. One concern per container: the web app, the worker and the database are separate containers, scaled and restarted independently.
  2. Treat containers as disposable: any state that matters lives in volumes or external services; you can delete and recreate a container at any time.
  3. Log to stdout/stderr and configure log rotation.
  4. Configure through the environment and validate at start-up.
  5. Set resource limits and a restart policy for long-running services.
  6. Publish only what must be public, binding admin ports to 127.0.0.1.
  7. Handle SIGTERM for graceful shutdown.

A best-practice linter

Tools like hadolint and docker build --check enforce rules like these automatically. Here is a compact version with a few of the most valuable rules:

python · try it yourself
import re

def lint(dockerfile):
    lines = [l.strip() for l in dockerfile.strip().splitlines() if l.strip() and not l.strip().startswith("#")]
    problems = []
    instructions = [l.split()[0].upper() for l in lines]

    for n, line in enumerate(lines, start=1):
        word, _, args = line.partition(" ")
        word = word.upper()
        if word == "FROM":
            image = args.split()[0]
            if ":" not in image.split("/")[-1] and "@" not in image and image != "scratch":
                problems.append((n, "DL3006", f"pin a tag for '{image}'"))
            elif image.endswith(":latest"):
                problems.append((n, "DL3007", "avoid the 'latest' tag"))
        if word == "RUN" and "apt-get install" in args:
            if "--no-install-recommends" not in args:
                problems.append((n, "DL3015", "add --no-install-recommends"))
            if "rm -rf /var/lib/apt/lists" not in args:
                problems.append((n, "DL3009", "delete apt lists in the same RUN"))
        if word == "RUN" and re.search(r"\bpip install\b", args) and "--no-cache-dir" not in args:
            problems.append((n, "DL3042", "use pip install --no-cache-dir"))
        if word == "ADD" and not re.match(r"(https?://|\S+\.tar)", args):
            problems.append((n, "DL3020", "use COPY instead of ADD for files"))
        if word in ("CMD", "ENTRYPOINT") and not args.startswith("["):
            problems.append((n, "DL3025", f"use exec (JSON) form for {word}"))
        if word == "RUN" and args.startswith("cd "):
            problems.append((n, "DL3003", "use WORKDIR instead of cd"))
        if word in ("ENV", "ARG") and re.search(r"(?i)(password|secret|token)", args):
            problems.append((n, "SEC01", "secret in ARG/ENV"))

    if "USER" not in instructions:
        problems.append((len(lines), "DL3002", "no USER: the container will run as root"))
    if "HEALTHCHECK" not in instructions:
        problems.append((len(lines), "INFO", "consider adding a HEALTHCHECK"))
    return problems

BEFORE = """
FROM python
RUN apt-get update && apt-get install -y gcc
ADD . /app
RUN cd /app && pip install -r requirements.txt
ENV DB_PASSWORD=hunter2
CMD python /app/app.py
"""

AFTER = """
FROM python:3.12-slim
RUN apt-get update && apt-get install -y --no-install-recommends gcc && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
USER 10001
HEALTHCHECK CMD python -c "import urllib.request as u; u.urlopen('http://localhost:8000/health')"
CMD ["python", "app.py"]
"""

for label, text in [("before", BEFORE), ("after", AFTER)]:
    found = lint(text)
    print(f"{label}: {len(found)} problem(s)")
    for line, code, message in found:
        print(f"  line {line}: {code} {message}")
before: 10 problem(s)
  line 1: DL3006 pin a tag for 'python'
  line 2: DL3015 add --no-install-recommends
  line 2: DL3009 delete apt lists in the same RUN
  line 3: DL3020 use COPY instead of ADD for files
  line 4: DL3042 use pip install --no-cache-dir
  line 4: DL3003 use WORKDIR instead of cd
  line 5: SEC01 secret in ARG/ENV
  line 6: DL3025 use exec (JSON) form for CMD
  line 6: DL3002 no USER: the container will run as root
  line 6: INFO consider adding a HEALTHCHECK
after: 0 problem(s)

Scoring a whole project

Beyond the Dockerfile, a short audit of the surrounding setup catches the remaining classics:

python · try it yourself
project = {
    ".dockerignore exists": True,
    ".dockerignore excludes .git": True,
    ".dockerignore excludes .env": False,
    "image tag is not latest": True,
    "compose sets restart policy": True,
    "compose sets memory limit": False,
    "db port bound to 127.0.0.1 or not published": False,
    "secrets via files, not environment": False,
    "log rotation configured": True,
    "image scanned in CI": True,
}

passed = [k for k, v in project.items() if v]
failed = [k for k, v in project.items() if not v]
score = 100 * len(passed) // len(project)
print(f"score: {score}/100 ({len(passed)} of {len(project)} checks)")
print("to do:")
for item in failed:
    print("  -", item)
score: 60/100 (6 of 10 checks)
to do:
  - .dockerignore excludes .env
  - compose sets memory limit
  - db port bound to 127.0.0.1 or not published
  - secrets via files, not environment

Anti-patterns to recognise

Anti-pattern Why it hurts Do instead
docker commit to make images unreproducible, nobody knows what's inside a Dockerfile in Git
SSH server inside the container extra attack surface, extra process docker exec / docker debug
Many processes under a supervisor in one container can't scale or restart parts independently one process per container + Compose
Editing files inside running containers changes vanish on recreate change the image or a mounted config
Data in the container's writable layer lost on docker rm volumes
:latest in production unknown version, surprise upgrades immutable version tags or digests

Test yourself

Which of these is a container best practice?

  1. Store the database files in the container's writable layer
  2. Run the web app, worker and database in separate containers
  3. Install an SSH server for debugging
  4. Use docker commit to save changes

A linter flags CMD python app.py. What is the fix?

  1. Use RUN python app.py
  2. Use exec form: CMD ["python", "app.py"]
  3. Remove CMD
  4. Use ENTRYPOINT with shell form

Why is RUN cd /app && make flagged in favour of WORKDIR /app?

  1. cd is not installed
  2. The cd only affects that one RUN; WORKDIR applies to all later instructions and is clearer
  3. WORKDIR is faster
  4. make requires WORKDIR