Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 111 ยท Dockerfiles

Writing a Dockerfile

Write your first Dockerfile and build it with docker build. Learn FROM, WORKDIR, COPY, RUN and CMD, how each line becomes a layer, and how to read build errors.

So far you have used images that other people built. A Dockerfile is the text file that lets you build your own. It is a short, readable recipe: start from this base image, copy these files in, run these commands, and when a container starts, run this program. Docker follows the recipe from top to bottom and produces an image you can run anywhere.

Writing a Dockerfile is the most useful single skill in Docker, because it turns "it works on my machine" into a file that anyone can rebuild. In this lesson you will write a small one, build it, run it, read the build output, and learn what happens when a line fails. The rest of the Dockerfile section builds on the five instructions you meet here.

A first Dockerfile

Make a new empty folder with two files. The first is a small shell script, greet.sh:

Terminal
#!/bin/sh
name="${1:-world}"
echo "Hello, $name!"
echo "Running on $(. /etc/os-release && echo $PRETTY_NAME)"

The second is a file named exactly Dockerfile (capital D, no extension):

DOCKERFILE
FROM alpine:3.22

WORKDIR /app
COPY greet.sh .
RUN chmod +x greet.sh

CMD ["./greet.sh"]

Read it as a story. FROM alpine:3.22 says "start with the Alpine Linux 3.22 image". WORKDIR /app says "from now on, work in /app (create it if needed)". COPY greet.sh . copies the script from your folder into /app. RUN chmod +x greet.sh makes it executable while the image is being built. CMD ["./greet.sh"] records the default command for containers started from this image.

Lines starting with # are comments, and blank lines are ignored. Instruction names are case-insensitive, but by convention they are written in capitals so they stand out from the arguments.

Building an image

docker build reads the Dockerfile and creates the image. Two arguments matter: -t gives the image a name (and optionally a tag), and the last argument is the build context folder, usually . for "the current folder":

CONSOLE
$ docker build -t greeter:1.0 .

Docker sends the files in that folder to the builder (that is the build context; the next lesson explains it fully), then executes each instruction. When output is not a terminal, BuildKit prints a plain log. We have shortened it here by removing the progress lines that only repeat timings:

CONSOLE
$ docker build -t greeter:1.0 .
#1 [internal] load build definition from Dockerfile
#1 DONE 0.0s
#2 [internal] load metadata for docker.io/library/alpine:3.22
#2 DONE 0.0s
#3 [internal] load .dockerignore
#3 DONE 0.0s
#4 [internal] load build context
#4 DONE 0.0s
#5 [1/4] FROM docker.io/library/alpine:3.22@sha256:2e0b81d6...
#5 DONE 0.0s
#6 [2/4] WORKDIR /app
#6 CACHED
#7 [3/4] COPY greet.sh .
#7 DONE 0.1s
#8 [4/4] RUN chmod +x greet.sh
#8 DONE 0.5s
#9 naming to docker.io/library/greeter:1.0 done

The numbers in brackets, [1/4] to [4/4], are the four instructions of your Dockerfile. The [internal] steps are BuildKit's housekeeping. On an interactive terminal you see the same steps as a live, colourful progress view instead. The important line is the last one: the image was named docker.io/library/greeter:1.0 (which docker images shows as greeter:1.0).

Run it:

CONSOLE
$ docker run --rm greeter:1.0
Hello, world!
Running on Alpine Linux v3.22

Anything after the image name replaces CMD, so you can pass your own command, and here that is the script with an argument:

CONSOLE
$ docker run --rm greeter:1.0 ./greet.sh Docker
Hello, Docker!
Running on Alpine Linux v3.22

The five instructions, one by one

FROM: choose the starting point

Every Dockerfile starts with FROM. It names the base image that your image is built on top of. Everything in the base image (its files, its package manager, its default user) becomes part of your image. Choosing a good base is a topic of its own: see Choosing a Base Image. Always give a tag. Plain FROM alpine means alpine:latest, which moves over time (Tags and Registries explains why that hurts).

The special base FROM scratch means "start with an empty filesystem", which is how tiny images for single static binaries are made.

WORKDIR: set the working directory

WORKDIR /app creates /app if it does not exist and makes it the current directory for the instructions that follow and for the container when it runs. Prefer it over RUN cd /app, because cd in a RUN only lasts for that one command. The default directory of a container comes from the image:

CONSOLE
$ docker run --rm greeter:1.0 pwd
/app

COPY: bring files into the image

COPY <source> <destination> copies files from the build context into the image. Sources are relative to the context folder; the destination is relative to WORKDIR when it is not absolute. Here COPY greet.sh . put the file in /app, which we can check:

CONSOLE
$ docker run --rm --entrypoint /bin/sh greeter:1.0 -c 'ls -l /app'
total 4
-rwxr-xr-x    1 root     root           110 Oct 23 14:15 greet.sh

(We used --entrypoint to run a different program instead of the script; you will learn about entrypoints in CMD and ENTRYPOINT.) COPY has more options, covered in COPY and ADD.

RUN: execute a command at build time

RUN executes a command while the image is being built and saves the result, any files it created or changed, as a new layer. Typical uses are installing packages, compiling code or changing permissions. The command runs once, at build time, not every time a container starts. RUN has important details (shell form versus exec form, chaining commands); see FROM and RUN.

CMD: the default command of a container

CMD sets what a container runs when you start it without specifying a command. It does not run during the build. A Dockerfile can have many RUN lines but only the last CMD counts. The ["./greet.sh"] format (a JSON array, called exec form) is the one you should use. You can read the stored value back from the image:

CONSOLE
$ docker image inspect greeter:1.0 --format '{{.Config.WorkingDir}} {{.Config.Cmd}}'
/app [./greet.sh]

One instruction, one layer

Each instruction that changes the filesystem creates a layer, a stack of file changes (see Layers and the Union Filesystem). docker history lists them from newest to oldest, one row per instruction, with the base image's own layers at the bottom:

CONSOLE
$ docker history greeter:1.0
IMAGE          CREATED         CREATED BY                                      SIZE      COMMENT
9175be708ee4   4 seconds ago   CMD ["./greet.sh"]                              0B        buildkit.dockerfile.v0
<missing>      4 seconds ago   RUN /bin/sh -c chmod +x greet.sh # buildkit     4.1kB     buildkit.dockerfile.v0
<missing>      4 seconds ago   COPY greet.sh . # buildkit                      12.3kB    buildkit.dockerfile.v0
<missing>      8 seconds ago   WORKDIR /app                                    8.19kB    buildkit.dockerfile.v0
<missing>      41 hours ago    CMD ["/bin/sh"]                                 0B        buildkit.dockerfile.v0
<missing>      41 hours ago    ADD alpine-minirootfs-3.22.7-x86_64.tar.gz /โ€ฆ   8.97MB    buildkit.dockerfile.v0

(Times and the image ID will differ on your machine.) CMD adds no data, so it is 0 B. The <missing> entries are normal: they are layers whose intermediate images do not exist locally as separate images.

Rebuilding is fast

Build the same Dockerfile again and Docker reuses every step whose inputs did not change:

CONSOLE
$ docker build -t greeter:1.0 .
...
#6 [2/4] WORKDIR /app
#6 CACHED
#7 [3/4] COPY greet.sh .
#7 CACHED
#8 [4/4] RUN chmod +x greet.sh
#8 CACHED

Now append a line to greet.sh and build again. The COPY step sees a different file, so it runs again, and so does everything after it. Steps before it stay cached:

CONSOLE
#6 [2/4] WORKDIR /app
#6 CACHED
#7 [3/4] COPY greet.sh .
#7 DONE 0.0s
#8 [4/4] RUN chmod +x greet.sh
#8 DONE 0.4s

That behaviour is the build cache, and ordering your instructions to make the most of it is the subject of The Build Cache.

Docker builds with BuildKit, the default builder since Docker 23. If you see #0 building with "desktop-linux" instance using docker driver at the top, that is just BuildKit naming the builder it uses on Docker Desktop. On other setups the builder name differs.

Naming the Dockerfile and the context

By default Docker looks for a file called Dockerfile at the root of the context. Use -f to pick another file (handy for Dockerfile.dev and Dockerfile.prod), and give -t more than once to apply several tags:

Terminal
docker build -f Dockerfile.dev -t greeter:dev .
docker build -t greeter:1.0 -t greeter:latest .

Pass -q to print only the new image ID, which is useful in scripts:

CONSOLE
$ docker build -q -t greeter:1.1 .
sha256:51288a6f3c49...

Reading build errors

Builds fail, and the messages are precise once you know where to look. Docker shows the failing instruction with the line number and an arrow, then the reason.

A RUN command that exits with a non-zero status stops the build, and the exit code is in the message:

CONSOLE
$ docker build -t bad .
Dockerfile:2
--------------------
   1 |     FROM alpine:3.22
   2 | >>> RUN exit 3
   3 |     
--------------------
ERROR: failed to build: failed to solve: process "/bin/sh -c exit 3" did not complete successfully: exit code: 3

A COPY of a file that is not in the build context fails with not found:

CONSOLE
ERROR: failed to build: failed to solve: failed to compute cache key: failed to calculate checksum of ref ...: "/nothere.txt": not found

A misspelled instruction is caught before anything runs, and Docker even suggests the fix:

CONSOLE
ERROR: failed to build: failed to solve: dockerfile parse error on line 2: unknown instruction: RNU (did you mean RUN?)

A Dockerfile whose first real instruction is not FROM (or ARG before it) has nothing to build on:

CONSOLE
ERROR: failed to build: failed to solve: no build stage in current context

And a wrong -f path reports the file it could not open:

CONSOLE
ERROR: failed to build: failed to solve: failed to read dockerfile: open nofile: no such file or directory

When an image build fails, nothing named by -t is created, but the layers of the steps that did succeed stay in the cache, so the retry resumes quickly.

Common beginner mistakes

  • Expecting RUN to run at container start. RUN is for build time. Use CMD (or ENTRYPOINT) for the program that runs when the container starts.
  • A file named dockerfile or Dockerfile.txt. Docker looks for Dockerfile by default. On case-sensitive systems, dockerfile is not found; use -f if you want another name.
  • Forgetting the context argument. docker build -t app without a path fails with ERROR: docker: 'docker buildx build' requires 1 argument. Add ..
  • Using latest or no tag in FROM. The build is then different every time the base image changes.
  • Copying the whole project with COPY . . before anything else. It works, but any edited file invalidates the cache from that point on. You will fix this in The Build Cache.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does RUN chmod +x greet.sh do in a Dockerfile?

    RUN executes at build time. Its result becomes a layer of the image. The default command at container start is set by CMD or ENTRYPOINT.
  2. 2. In docker build -t greeter:1.0 ., what is the final . for?

    The last argument of docker build is the build context. . means the current folder. The Dockerfile is looked up inside it by default.
  3. 3. You edit greet.sh and rebuild. Which steps run again?

    Docker caches each step by its inputs. The COPY input changed, so that step and all steps after it are rebuilt. The steps before it stay cached.
  4. 4. How many CMD instructions take effect in a Dockerfile that has three?

    Only the last CMD counts. It is the default command of containers started from the image.
  5. 5. What does WORKDIR /app do?

    WORKDIR creates the directory if needed and keeps it as the working directory for later instructions and for the container's process. Unlike cd in a RUN, it persists.

Summary

  • A Dockerfile is a text recipe: FROM a base image, then instructions such as WORKDIR, COPY, RUN and CMD.
  • docker build -t name:tag . builds the image from the Dockerfile in the context folder; -f picks another Dockerfile, -q prints only the ID.
  • RUN happens at build time and creates a layer; CMD is the default command at container start.
  • docker history shows one row per instruction. Unchanged steps are reused from the cache; once a step changes, later steps rebuild.
  • Build errors name the failing line. Typos, missing files and failing commands each produce a distinct message.
  • Always tag your FROM image and keep the Dockerfile next to the code it builds.

Next: Build Context and .dockerignore