Course contents · Lesson 3 of 22

Dockerfile Basics: Build Your First Image, Hands-On

Working with Docker · Lesson 3 of 22 · 12 min Engineer

You wrote a small Python web app, and a teammate needs to run it. What Is Docker? showed that Docker ships apps as images, but how do you make one? This lesson covers Dockerfile basics: write one, build an image, run it, and learn habits that keep images small and safe.

Anatomy of a small Dockerfile

A Dockerfile is a text file, normally named just Dockerfile, listing the instructions that build an image, one per line.

Your app uses Flask, a small Python library for websites. In an empty folder, say myapp, save this as app.py:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello from my container\n"

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

It answers on port 8000. A port is a numbered door that network traffic is addressed to, and 0.0.0.0 means "listen on every network address". Next to it, save requirements.txt, the list of Python dependencies, with one line, flask==3.1.0; the == pins an exact version. Then save this as Dockerfile:

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN useradd --create-home appuser
USER appuser
EXPOSE 8000
CMD ["python", "app.py"]

The diagram explains each line; notice that six build steps change files, while the last three only store settings for start time.

The nine-line Dockerfile with an arrow from each line to a note. FROM python:3.12-slim: base image, Python 3.12 on slim Debian. WORKDIR /app: work in /app, created if missing. COPY requirements.txt: copy the dependency list in first. RUN pip install: build time, install Flask. COPY . .: copy the rest of your code. RUN useradd: build time, add a normal user. These six are build steps. USER appuser: run as appuser, not root. EXPOSE 8000: documents the port, publishes nothing. CMD: start time, the default command. These three are settings
Six lines build files; the last three are settings for start time.

FROM names the base image yours builds on: the official Python image with tag (version label) 3.12-slim, meaning Python 3.12 on trimmed-down Debian Linux. WORKDIR sets the working directory, the folder later steps and the app run in, creating it if needed.

COPY copies files from your folder into the image; copying requirements.txt before the rest speeds up rebuilds, as Docker Image Layers and Caching explains. RUN runs a command during the build and keeps the files it creates: pip, Python's package installer, installs Flask (--no-cache-dir keeps pip's download cache out of the image), then useradd adds an ordinary user.

USER makes later steps and the app run as that user. EXPOSE only documents the app's port; it opens nothing.

RUN vs CMD vs ENTRYPOINT

RUN acts at build time: its command runs once, while the image is made, and only the result is kept. CMD and ENTRYPOINT act at start time: they store a command that runs whenever a container starts.

CMD is a replaceable default: anything after the image name in docker run replaces it. So, once built, docker run --rm myapp python --version prints a line beginning Python 3.12. instead of starting the server. Only the last CMD counts.

ENTRYPOINT fixes the program: what you type after the image name is added to it as arguments, and CMD only supplies default arguments. It suits an image that is a tool for one job; docker run --entrypoint can still swap it. The flowchart shows both.

Flowchart. Question: should every container run one fixed program? No: use CMD, such as CMD python app.py in the image myapp. docker run myapp runs python app.py; docker run myapp python --version runs python --version, because arguments replace CMD. Yes: use ENTRYPOINT echo hello with CMD world as default arguments, in the image greet. docker run greet runs echo hello world; docker run greet there runs echo hello there, because arguments replace only CMD. Notes: write both in exec form; --entrypoint swaps the program
Arguments after the image name always replace CMD; an ENTRYPOINT stays and receives them.

Write both as a JSON list, the exec form, which starts your program directly. The shell form, CMD python app.py, wraps it in /bin/sh -c, so your app may miss the stop signal from docker stop, and a shell-form ENTRYPOINT ignores CMD and arguments.

Build the image and run a container

Open a terminal in myapp and build. -t myapp names the image (with no tag, Docker adds latest). The final dot is the build context: the folder whose files are sent to the builder, the only files COPY can see, and where Docker looks for the Dockerfile.

docker build -t myapp .

Docker runs the build steps top to bottom; the first build also downloads the base image. You should see something like this (trimmed; details vary by Docker version):

[+] Building 21.4s (11/11) FINISHED
 => [1/6] FROM docker.io/library/python:3.12-slim@sha256:…
 => => transferring context: 1.05kB
 => [4/6] RUN pip install --no-cache-dir -r requirements.txt
 => [6/6] RUN useradd --create-home appuser
 => => naming to docker.io/library/myapp:latest

Only build steps get numbers; transferring context shows the build context's size. Forget the dot and Docker complains that it requires exactly 1 argument; in the wrong folder, the error ends in open Dockerfile: no such file or directory. The diagram follows the whole journey.

Six numbered steps. 1: the build context, this folder with Dockerfile, app.py, requirements.txt and .dockerignore, is sent to the builder. 2: docker build -t myapp . runs steps 1 to 6 top to bottom and saves USER, EXPOSE and CMD. 3: the result is the read-only image myapp:latest. 4: docker run --rm -p 127.0.0.1:8080:8000 myapp starts a container from it. 5: the container runs python app.py, listening on port 8000. 6: on your laptop, curl localhost:8080 reaches it, as port 8080 forwards to 8000
Build once; each docker run starts a fresh container from that one image.

Now run it. --rm deletes the container when it stops. -p publishes a port, forwarding traffic from your laptop to the container, written laptop:container, here 8080 to 8000. The leading 127.0.0.1 keeps it private to your machine; plain -p 8080:8000 also accepts other devices on your network.

docker run --rm -p 127.0.0.1:8080:8000 myapp

The app's log appears (trimmed below; Flask also warns that this server is for development only). The addresses it lists are the container's own, not your laptop's:

 * Serving Flask app 'app'
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:8000
 * Running on http://172.17.0.2:8000
Press CTRL+C to quit

In a second terminal, run curl http://localhost:8080 (curl downloads a web address; a browser works too). You should get:

Hello from my container

Press Ctrl+C in the first terminal to stop. If Docker says port is already allocated, choose another laptop port, such as 127.0.0.1:8081:8000. If curl gets an empty reply or a reset connection, Docker accepted it but found nothing listening on the container's port 8000. A classic cause is an app bound to 127.0.0.1, the app.run() default, which inside a container means the container alone. Hence host="0.0.0.0".

Keep junk and secrets out with .dockerignore

COPY . . copies the whole build context, including things you never meant to ship: Git history, Python caches, a virtual environment, or a .env file of passwords. Anyone with the image can read its files, and deleting one in a later step does not remove it from the step that added it.

A .dockerignore file in the root of the build context lists patterns to leave out, one per line. Matching files never reach the builder, so COPY cannot copy them. Save this next to your Dockerfile:

.git
.venv
**/__pycache__
**/*.pyc
.env
**/*.pem

Unlike in .gitignore, a pattern without **/ matches only at the top of the context. If a COPY later fails with not found, check whether a pattern excludes that file.

Good habits for every Dockerfile

Start small. A slim or Alpine base holds fewer programs, so it downloads faster and gives attackers less to use. For Python, Debian-based -slim is a safe default: Alpine is smaller, but its musl C library means some Python packages need extra build tools.

Pin versions. FROM python means python:latest and a bare flask means the newest Flask, so next month's build can differ. Even 3.12-slim moves with patch releases; for exactly the same base, pin its digest, a fingerprint of the image's content: python:3.12-slim@sha256:….

Run as a non-root user. Without USER, the app runs as root, the all-powerful administrator account. Containers share the host's kernel (lesson 1), so an attacker who escapes through a kernel flaw arrives as root on the host. Check yours by replacing CMD with whoami, which prints the current user:

docker run --rm myapp whoami

You should see:

appuser

If it prints root, add the USER line and rebuild.

One main process per container. A container lives as long as its main process, and Docker stops, restarts and logs it as one unit. So a database gets its own container; Docker Compose Basics runs such a pair.

Check yourself

You add RUN python app.py to the Dockerfile to start the server. What happens at build time?

The build never finishes: RUN waits for its command to end, and a web server keeps running. Start commands belong in CMD.

Your image says EXPOSE 8000, but after docker run --rm myapp, http://localhost:8000 does not answer. Why?

EXPOSE only documents the port; nothing reaches the container from your laptop until you publish it, for example with -p 127.0.0.1:8000:8000.

The greet image has ENTRYPOINT ["echo", "hello"]. What does docker run --rm greet echo bye print?

hello echo bye: arguments replace only CMD and go after the entrypoint; swapping the program needs --entrypoint.