TExcelTAD
Home › Docker › Dockerfile Basics

Dockerfile Basics

A Dockerfile is a plain-text recipe for building an image. Each line is an instruction followed by its arguments. Docker reads the file from top to bottom, and each instruction either changes the filesystem (creating a new layer) or changes the image's metadata.

Here is a complete Dockerfile for a small Python web service:

dockerfile
# syntax=docker/dockerfile:1
FROM python:3.12-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

EXPOSE 8000
CMD ["python", "-m", "http.server", "8000"]

Build it and run it:

bash
docker build -t hello-py:1.0 .
docker run --rm -p 8000:8000 hello-py:1.0

Sample output of the build (BuildKit, abridged):

text
[+] Building 14.2s (10/10) FINISHED
 => [internal] load build definition from Dockerfile                  0.0s
 => [internal] load metadata for docker.io/library/python:3.12-slim    1.1s
 => [1/5] FROM docker.io/library/python:3.12-slim@sha256:...           4.3s
 => [internal] load build context                                      0.0s
 => [2/5] WORKDIR /app                                                 0.1s
 => [3/5] COPY requirements.txt .                                      0.0s
 => [4/5] RUN pip install --no-cache-dir -r requirements.txt           7.9s
 => [5/5] COPY . .                                                     0.0s
 => exporting to image                                                 0.4s
 => => naming to docker.io/library/hello-py:1.0                        0.0s

The final . in docker build -t hello-py:1.0 . is the build context: the folder whose files are sent to the builder and may be copied into the image. -t gives the result a name and tag.

Syntax rules

Rule Example
Instructions are case-insensitive, but written in UPPERCASE by convention RUN, COPY
A Dockerfile must start with FROM (only ARG, comments and parser directives may come before it) FROM node:22-alpine
# at the start of a line is a comment # install deps
A trailing backslash continues the instruction on the next line RUN apt-get update && \
# syntax=... on the very first line is a parser directive that selects the Dockerfile frontend version # syntax=docker/dockerfile:1

A tiny Dockerfile parser

To understand how Docker reads the file, here is a parser that handles comments, line continuations and instruction names, and reports which instructions add filesystem layers.

python · try it yourself
DOCKERFILE = """\
# syntax=docker/dockerfile:1
FROM python:3.12-slim
WORKDIR /app
# dependencies first, for caching
COPY requirements.txt .
RUN pip install --no-cache-dir \\
        -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "app.py"]
"""

FILESYSTEM = {"RUN", "COPY", "ADD", "WORKDIR"}

def parse(text):
    steps, buffer = [], ""
    for line in text.splitlines():
        stripped = line.strip()
        if not buffer and (not stripped or stripped.startswith("#")):
            continue
        if stripped.endswith("\\"):
            buffer += stripped[:-1].strip() + " "
            continue
        full = buffer + stripped
        buffer = ""
        name, _, args = full.partition(" ")
        steps.append((name.upper(), args.strip()))
    return steps

for number, (name, args) in enumerate(parse(DOCKERFILE), start=1):
    kind = "layer" if name in FILESYSTEM else "metadata"
    print(f"{number}. {name:<8} {kind:<9} {args}")
1. FROM     metadata  python:3.12-slim
2. WORKDIR  layer     /app
3. COPY     layer     requirements.txt .
4. RUN      layer     pip install --no-cache-dir -r requirements.txt
5. COPY     layer     . .
6. EXPOSE   metadata  8000
7. CMD      metadata  ["python", "app.py"]

The two physical lines of the RUN instruction became one logical step, and the comments disappeared. (WORKDIR creates the directory if needed, which is why it counts as a filesystem step here; when the folder already exists it produces an empty layer.)

Shell form vs exec form

RUN, CMD and ENTRYPOINT accept two forms:

Form Example How it runs
Shell form RUN apt-get update && apt-get install -y curl wrapped in /bin/sh -c "...": pipes, && and $VARS work
Exec form CMD ["python", "app.py"] a JSON array, executed directly with no shell

Exec form must be valid JSON: double quotes, not single quotes. CMD ['python', 'app.py'] is not valid JSON, so Docker silently treats it as shell form and the container tries to run a program called ['python',. The check below shows how Docker decides:

python · try it yourself
import json

def run_form(args):
    try:
        value = json.loads(args)
        if isinstance(value, list) and all(isinstance(v, str) for v in value):
            return "exec ", value
    except json.JSONDecodeError:
        pass
    return "shell", ["/bin/sh", "-c", args]

for args in ['["python", "app.py"]',
             "['python', 'app.py']",
             'python app.py --port $PORT']:
    form, argv = run_form(args)
    print(f"{form} {argv}")
exec  ['python', 'app.py']
shell ['/bin/sh', '-c', "['python', 'app.py']"]
shell ['/bin/sh', '-c', 'python app.py --port $PORT']

Tip: use exec form for CMD and ENTRYPOINT so your program runs as PID 1 and receives stop signals directly. Use shell form for RUN when you need shell features.

Linting your Dockerfile

docker build --check . runs Docker's built-in build checks (for example, a FROM with mismatched AS casing or a JSON-looking CMD that is not valid JSON) without building. The community tool hadolint goes further and also lints the shell commands inside RUN.

bash
docker build --check .
docker run --rm -i hadolint/hadolint < Dockerfile

Test yourself

In docker build -t shop:1.0 ., what does the final . mean?

  1. The image name
  2. The build context: the folder sent to the builder
  3. Build all Dockerfiles in the folder
  4. The current tag

Why does CMD ['node', 'server.js'] fail?

  1. CMD needs exactly one argument
  2. Single quotes are not valid JSON, so Docker treats it as shell form
  3. Node is not allowed in CMD
  4. CMD must come before FROM

Which instruction must (almost always) come first in a Dockerfile?

  1. RUN
  2. WORKDIR
  3. FROM
  4. CMD