Docker Basics: Containers Made Simple
Writing a Dockerfile
In this lesson you will
- Write a simple Dockerfile
- Build an image and run a container from it
- Use .dockerignore and layer caching well
Introduction
So far you ran images made by others. To package your own app, you write a Dockerfile: a text file of step-by-step instructions that builds an image.
An example app
Imagine a tiny Python web app in a folder with two files: app.py and requirements.txt. Here is a Dockerfile for it:
Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "app.py"]What each line does:
FROMpicks the base image to start from. Here, Python 3.12 in a small version.WORKDIRsets the working folder inside the image.COPY requirements.txt .copies that one file in first.RUNruns a command while building, here installing libraries.COPY . .copies the rest of your code.CMDis the command that runs when a container starts.
Build and run
From the folder that holds the Dockerfile:
Terminal
$ docker build -t my-app .
$ docker run -p 5000:5000 my-app-t my-app gives the image a name (a tag), and the dot at the end means "use this folder". Use the port your app actually listens on.
Quick quiz
What does the FROM line in a Dockerfile do?
Why copy requirements first?
Docker builds an image in layers and caches each one. If a layer and everything before it is unchanged, Docker reuses it. Your code changes often, but your dependencies change rarely. Copying and installing dependencies before copying the code means a code change does not trigger a slow reinstall.
Keep images clean
Create a .dockerignore file to leave things out of the build, similar to .gitignore:
.git
node_modules
__pycache__
.envNever bake secrets, such as passwords or API keys, into an image. Pass them in when the container runs instead, for example with -e NAME=value or a secrets tool, because anyone who gets the image could read what is inside.
Try it yourself
Write a Dockerfile for a small app in a language you know. Build it, run it and check it works. Then change one line of code and rebuild. Notice which steps Docker reuses from its cache.
Summary
- A Dockerfile lists the steps to build an image, starting with FROM.
docker build -t name .builds it, anddocker runstarts a container from it.- Order steps so slow, rarely changing ones come first, and keep secrets out of images.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading