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:
- Start from a system with Python.
- Install the dependencies (Flask).
- Copy the application code.
- 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"]
| Instruction | What it does |
|---|---|
FROM | The base image. Every Dockerfile starts here: an operating system or, better, an image that already includes the language. |
WORKDIR | The working folder for the following instructions and for the container. |
COPY | Copies files from your folder (the context) into the image. |
RUN | Runs a command during the build, such as installing packages. |
EXPOSE | Documents the port the application listens on. It does not publish it: that is still -p. |
CMD | The 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.
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
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.txtis copied and installed beforeapp.pyfor 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.
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
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 is replaced entirely; ENTRYPOINT stays and receives the arguments. Diagram: The House of Routing.
| In the Dockerfile | docker run image | docker run image 10 |
|---|---|---|
CMD ["sleep","5"] | sleep 5 | 10 (error: not a command) |
ENTRYPOINT ["sleep"] | sleep (error: missing argument) | sleep 10 |
ENTRYPOINT ["sleep"] + CMD ["5"] | sleep 5 | sleep 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 .
Dockerfile cheat sheet
| You need to | Use |
|---|---|
| Choose the base | FROM python:3.13-slim |
| Set the working folder | WORKDIR /app |
| Add files | COPY requirements.txt . |
| Install something at build time | RUN pip install -r requirements.txt |
| Default configuration value | ENV MESSAGE="..." |
| Startup command | CMD ["python", "app.py"] |
| Fixed executable with arguments | ENTRYPOINT ["sleep"] + CMD ["5"] |
| Build / see layers | docker build -t name:tag . / docker history |
| Publish | docker 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:
CMDdefines it and is replaced entirely;ENTRYPOINTfixes the executable. - To share:
docker tagwith your username anddocker 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
- Dockerfile referencedocs.docker.com
- Building best practicesdocs.docker.com
- Docker build cachedocs.docker.com
- docker buildx builddocs.docker.com
- docker image pushdocs.docker.com
- Personal access tokensdocs.docker.com
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.