Skip to content
Lesson: Dockerfile BasicsSwitch
← DevOps Operations

Delivery and containers

Dockerfile Basics

Write a Dockerfile, build an image from it and understand layer caching.

A Dockerfile is a text file of instructions for building an image. Each build follows the same recipe, so you do not set up containers by hand.

A small example

Create a folder with hello.sh:

echo "Hello, $NAME"

Beside it, create a file named Dockerfile:

FROM alpine:3.20
WORKDIR /app
COPY hello.sh .
ENV NAME=world
CMD ["sh", "hello.sh"]

FROM picks the base image. WORKDIR sets the working directory, creating it if needed. COPY brings files from your build folder into the image. ENV sets an environment variable. CMD is the default command when a container starts.

Build and run

$ docker build -t hello:1 .
...
$ docker run --rm hello:1
Hello, world

-t names the image. The final . is the build context, the set of files the builder may copy. Build output varies between Docker versions. A .dockerignore file keeps unwanted files and secrets out of the context.

RUN happens at build time

RUN apk add --no-cache curl

RUN executes while the image is built and saves the result. CMD runs later, when a container starts. apk is Alpine's package tool; Debian based images use apt-get.

CMD and ENTRYPOINT

Arguments after the image name in docker run replace CMD. In its JSON form, ENTRYPOINT sets a program that stays in place, with those arguments added to it. You can override it with --entrypoint. Only the last CMD in a file takes effect.

Layer caching

Docker reuses earlier results when an instruction and its inputs are unchanged. Once one step changes, the steps after it run again. So copy the things that change rarely first:

COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .

This fragment assumes a Python base image. Editing your source code then does not reinstall the dependencies.

Do not put passwords in ENV or copy them into the image, because anyone with the image may be able to recover them. Consider adding a USER instruction so the application does not run as root.

The full list is in the Dockerfile reference.

Try it

Build the example, then run docker run --rm -e NAME=Sam hello:1. Change hello.sh, rebuild, and note which steps come from the cache.

Check your understanding

Dockerfile Basics

All 4 sections · no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.