DOCKER · DOCKER FROM SCRATCH · CHAPTER 4

Docker Images

From image user to image author: Dockerfile, layers, cache and your first published image.

8 min readCourse: Docker from ScratchLevel: beginner

From point A to point B

Point A: you can run any image from Docker Hub, but you depend on someone else having packaged your application for you. Point B: by the end of this chapter you will write a Dockerfile, build your own image, understand why the second build takes seconds and publish the result to a registry so anyone can run it.

This is the jump from Docker user to image author: from here on, any application you write can travel in a container.

Why build your own image

There are two common reasons:

  • There is no image for what you need. Docker Hub has thousands, but none of them contains your application.
  • You want your application to be easy to distribute. An image carries the code, the interpreter, the libraries and the configuration. Whoever runs it needs nothing installed but Docker.

Almost anything fits in an image: an API, a command-line tool, a web server, even a browser.

From manual steps to a Dockerfile

Before you write a Dockerfile, think about how you would install the application by hand on a brand-new server. For a small Python API with Flask, these would be the steps:

  1. Start from a system with Python.
  2. Install the dependencies (Flask).
  3. Copy the application code.
  4. Start the server.

Try it first inside a container, as you would on a server:

docker run -it -p 8080:8080 python:3.13-slim bash
# inside the container:
pip install flask
cat > /app.py      # paste the code below and press Ctrl+D
python /app.py

This is the code, a server with two routes:

# app.py
from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Welcome to The House of Routing\n"

@app.route("/health")
def health():
    return "ok\n"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)

If curl http://localhost:8080 answers from another terminal, the steps work. Now turn them into instructions in a file called Dockerfile, in the same folder as app.py and a requirements.txt that contains a single line: flask.

# Dockerfile
FROM python:3.13-slim

WORKDIR /app

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

COPY app.py .

EXPOSE 8080
CMD ["python", "app.py"]
InstructionWhat it does
FROMThe base image. Every Dockerfile starts here: an operating system or, better, an image that already includes the language.
WORKDIRThe working folder for the following instructions and for the container.
COPYCopies files from your folder (the context) into the image.
RUNRuns a command during the build, such as installing packages.
EXPOSEDocuments the port the application listens on. It does not publish it: that is still -p.
CMDThe command that runs when a container starts.

The format is always INSTRUCTION arguments. By convention, instructions are written in uppercase.

Building and running your image

# -t sets the name and tag; the final dot is the context: the current folder
docker build -t thor-api:1.0 .

docker images thor-api
docker run -d --name api -p 8080:8080 thor-api:1.0
curl http://localhost:8080/health

The final dot is not decoration: it tells Docker which folder to send to the builder. Only the files in that folder are available to COPY. If there are things you do not want to send (a virtual environment, .git, secrets), list them in a .dockerignore file.

Connecting to what you know. In chapter 1 you saw that an image is a read-only template. The Dockerfile is the recipe for that template: anyone with the file can rebuild exactly the same image.

Layers and cache: why order matters

Each instruction that changes files creates a layer, and each layer stores only the differences from the previous one. You can see your image's layers and how much space each one takes:

docker history thor-api:1.0
Image layers and the build cache Each Dockerfile instruction produces a layer. After app.py changes, the first four steps are reused from the cache and only COPY app.py and the steps after it are rebuilt. DOCKERFILESECOND BUILD FROM python:3.13-slim CACHED base layer WORKDIR /app CACHED 4 KB COPY requirements.txt . CACHED 4 KB RUN pip install -r requirements.txt CACHED 14 MB COPY app.py . REBUILT 4 KB CMD ["python", "app.py"] REBUILT 0 B · metadata app.py changed: this step and every step after it run again. Every step before it reuses its layer from the cache.

Each Dockerfile instruction produces a layer; if one changes, it and every layer above it are rebuilt. Diagram: The House of Routing.

Layers are stored in a cache. When you build again, Docker reuses every layer whose instructions and files have not changed, and rebuilds from the first one that did. That is why:

  • If the build fails halfway, when you fix it and run it again Docker does not repeat the steps that already finished successfully.
  • If you only change the code, the dependencies are not reinstalled. In the Dockerfile above, requirements.txt is copied and installed before app.py for exactly this reason.

Try it: edit the message in app.py and build again with the tag 1.1. You will see CACHED on the pip install steps and the build will take seconds.

Good to know. If you copied the whole project with a single COPY . . before the pip install, any change to the code would invalidate the dependency cache and reinstall them on every build. Order the Dockerfile from what changes least to what changes most.

Configuration with environment variables

Do not write configuration inside the code. If your application reads a value from an environment variable, the same image works for development, testing and production:

import os
MESSAGE = os.environ.get("MESSAGE", "Welcome to The House of Routing")

In the Dockerfile you can set a default value with ENV, and whoever runs the container changes it with -e, as you saw in the previous chapter:

ENV MESSAGE="Welcome to The House of Routing"
docker run -d -p 8081:8080 -e MESSAGE="Hello from testing" thor-api:1.1

# Which variables does a running container have?
docker inspect -f '{{json .Config.Env}}' api
Careful with secrets. Never put passwords in ENV or in the code: they get recorded in a layer, and anyone with the image can read them with docker history or docker inspect.

CMD and ENTRYPOINT: what runs at startup

A container is not a virtual machine: it is not meant to host a full operating system, but to run one process. The container lives as long as that process lives. When the process ends, the container stops.

docker run ubuntu       # starts and stops right away
docker ps -a            # Exited (0)

Why? The Ubuntu image starts bash, and bash without a terminal has nothing to do, so it ends. What runs at startup is decided by the image with CMD, and you can replace it by adding a command at the end of docker run:

docker run ubuntu sleep 5    # the container lives for 5 seconds

To make that behavior the default, build your own image:

FROM ubuntu:24.04
CMD ["sleep", "5"]

CMD accepts two forms. Use the second one, the exec form: a JSON list with double quotes, where the first element is the executable and each argument goes separately.

CMD sleep 5              # shell form: runs inside /bin/sh -c
CMD ["sleep", "5"]       # exec form: recommended

However, with CMD whoever runs the image has to rewrite the whole command to change a single number (docker run sleeper sleep 10). ENTRYPOINT solves that: it fixes the executable, and whatever you put in docker run is appended as an argument.

FROM ubuntu:24.04
ENTRYPOINT ["sleep"]
CMD ["5"]                # default value if you pass nothing
docker build -t sleeper .
docker run sleeper                           # sleep 5
docker run sleeper 10                        # sleep 10
docker run --entrypoint echo sleeper hello   # also changes the executable
CMD versus ENTRYPOINT With only CMD, arguments to docker run replace the whole command, so docker run img 10 tries to run 10. With ENTRYPOINT sleep and CMD 5, docker run img runs sleep 5 and docker run img 10 runs sleep 10. CMD ONLY ENTRYPOINT + CMD CMD ["sleep", "5"] ENTRYPOINT ["sleep"] CMD ["5"] docker run imgdocker run img sleep 5CMD as is sleep 5→ sleep 5 docker run img 10docker run img 10 10whole CMD replaced:"10" is not a command sleep 10→ sleep 10 fixed executable argument from docker run default from CMD

CMD is replaced entirely; ENTRYPOINT stays and receives the arguments. Diagram: The House of Routing.

In the Dockerfiledocker run imagedocker run image 10
CMD ["sleep","5"]sleep 510 (error: not a command)
ENTRYPOINT ["sleep"]sleep (error: missing argument)sleep 10
ENTRYPOINT ["sleep"] + CMD ["5"]sleep 5sleep 10

Publishing to a registry

Your image exists only on your machine. To share it, push it to a registry: Docker Hub, GitHub Container Registry or your cloud's registry. On Docker Hub, the image name starts with your username.

# 1. Log in (it will ask for an access token, not your password)
docker login -u YOUR_USER

# 2. Give the local image a registry name
docker tag thor-api:1.1 YOUR_USER/thor-api:1.1

# 3. Push it
docker push YOUR_USER/thor-api:1.1

# Now anyone can run it
docker run -d -p 8080:8080 YOUR_USER/thor-api:1.1

docker tag copies nothing: it adds another name that points to the same image. You can also build directly with the final name: docker build -t YOUR_USER/thor-api:1.1 .

Security. An access token is a credential: do not paste it into notes, repositories or chats. If it is ever exposed, revoke it from your account settings and create a new one. And use private repositories for anything that should not be public.

Dockerfile cheat sheet

You need toUse
Choose the baseFROM python:3.13-slim
Set the working folderWORKDIR /app
Add filesCOPY requirements.txt .
Install something at build timeRUN pip install -r requirements.txt
Default configuration valueENV MESSAGE="..."
Startup commandCMD ["python", "app.py"]
Fixed executable with argumentsENTRYPOINT ["sleep"] + CMD ["5"]
Build / see layersdocker build -t name:tag . / docker history
Publishdocker tag + docker push

Challenge

Answer before you open the solution. Getting it wrong here is the cheapest way to learn.

1. You change one line of app.py and rebuild. Why does pip install not run again?

Because of the layer cache. The instructions before COPY app.py did not change, so Docker reuses their layers and rebuilds only from that point.

2. What does the dot at the end of docker build -t thor-api:1.0 . mean?

The build context: the folder whose files are sent to the builder and become available to COPY.

3. You run docker run ubuntu and the container shows up as Exited right away. Why?

Because its process ended. The default command is bash, which has nothing to do without a terminal. A container lives only as long as its main process lives.

4. An image has ENTRYPOINT ["sleep"] and CMD ["5"]. What does docker run image 20 run?

sleep 20. The docker run argument replaces the CMD and is appended to the ENTRYPOINT.

5. What is the problem with ENV DB_PASSWORD=supersecret?

The password gets recorded in the image. Anyone who downloads it can see it with docker inspect or docker history. Pass it at run time or, better, with secret management.

What you take away

  • A Dockerfile turns installation steps into a repeatable recipe.
  • Each instruction creates a layer; the cache reuses the ones that did not change.
  • Order the Dockerfile from what changes least to what changes most: dependencies before code.
  • Configuration goes in environment variables; secrets never go in the image.
  • A container lives as long as its process: CMD defines it and is replaced entirely; ENTRYPOINT fixes the executable.
  • To share: docker tag with your username and docker push.

In the next chapter you stop launching containers one by one: a complete application, with several services, in a single file with Docker Compose.

Official resources

Source and credits. Chapter written from Jesús Espinoza's study notes on KodeKloud's Docker for Absolute Beginners course (December 2024). Text drafted with AI assistance; original diagrams by The House of Routing. Technical details were checked against the official Docker documentation.

Navigate