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
- Pin your base image to a specific version (
python:3.12.11-slim), or a digest for full reproducibility. Neverlatest. - Choose a small, maintained base:
-slim, distroless, or Alpine when your stack supports musl. - Use multi-stage builds so compilers and dev dependencies stay out of the runtime image.
- Order instructions for the cache: system packages → dependency manifests → install dependencies → source code.
- Combine and clean up in the same
RUN(apt-get update && apt-get install ... && rm -rf /var/lib/apt/lists/*). - Add a
.dockerignorewith.git,node_modules, build output,.envfiles. - Prefer
COPYoverADD, unless you need tar extraction or a checksummed URL. - Run as a non-root user (
USER 10001) and give files the right owner withCOPY --chown. - Use exec form for
CMD/ENTRYPOINTso signals reach your app. - Add
HEALTHCHECKand OCILABELs (version, source, revision). - No secrets in images: no
ARG/ENVpasswords, no copied keys. Use build secrets.
Containers
- One concern per container: the web app, the worker and the database are separate containers, scaled and restarted independently.
- Treat containers as disposable: any state that matters lives in volumes or external services; you can delete and recreate a container at any time.
- Log to stdout/stderr and configure log rotation.
- Configure through the environment and validate at start-up.
- Set resource limits and a restart policy for long-running services.
- Publish only what must be public, binding admin ports to
127.0.0.1. - Handle
SIGTERMfor 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?
- Store the database files in the container's writable layer
- Run the web app, worker and database in separate containers
- Install an SSH server for debugging
- Use
docker committo save changes
A linter flags CMD python app.py. What is the fix?
- Use
RUN python app.py - Use exec form:
CMD ["python", "app.py"] - Remove CMD
- Use ENTRYPOINT with shell form
Why is RUN cd /app && make flagged in favour of WORKDIR /app?
- cd is not installed
- The cd only affects that one RUN; WORKDIR applies to all later instructions and is clearer
- WORKDIR is faster
- make requires WORKDIR