Writing Your First Dockerfile
In modern software engineering, the phrase "it works on my machine" is a thing of the past. To deploy reliable applications across different environments—whether that is your local laptop, an AWS EC2 instance, or a Kubernetes cluster—we use containerization. At the heart of this process is the Dockerfile.
A Dockerfile is simply a plain text document that contains all the instructions needed to assemble a Docker image. Think of it as a recipe. By following this recipe, Docker guarantees that your application runs exactly the same way, everywhere.
- What a Dockerfile is and how it powers modern microservices.
- The core Dockerfile syntax:
FROM,WORKDIR,COPY,RUN, andCMD. - How to write a complete Dockerfile to containerize a Python application.
- Best practices for layer caching to speed up your deployment builds.
1. The Core Dockerfile Instructions
While Docker supports dozens of commands, you can build 95% of real-world applications using just a handful of core instructions. Each instruction in a Dockerfile creates a new "layer" in your image.
| Instruction | Purpose | Example Usage |
|---|---|---|
| FROM | Defines the base operating system or runtime to start from. Must be the first instruction. | FROM python:3.11-slim |
| WORKDIR | Sets the working directory inside the container for any subsequent commands. | WORKDIR /app |
| COPY | Copies files or folders from your local machine into the container's file system. | COPY . . |
| RUN | Executes commands inside the container during the build process (e.g., installing dependencies). | RUN pip install -r reqs.txt |
| CMD | Specifies the default command to run when the container actually starts up. | CMD ["python", "app.py"] |
2. Containerizing a Python Application
Let's build a practical example. Imagine you have a simple Python script named app.py that depends on an external library listed in a requirements.txt file. We want to package this into a container.
Writing the Dockerfile
Example 1: A production-ready Dockerfile
# Step 1: Start with a lightweight Python base image
FROM python:3.11-slim
# Step 2: Set the working directory inside the container
WORKDIR /app
# Step 3: Copy ONLY the requirements file first (Crucial for caching)
COPY requirements.txt .
# Step 4: Install the Python dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Step 5: Copy the rest of the application code
COPY . .
# Step 6: Define the command to run when the container starts
CMD ["python", "app.py"]
Expected output during "docker build -t my-python-app ."
[+] Building 4.2s (10/10) FINISHED => [internal] load build definition from Dockerfile => => transferring dockerfile: 284B => [internal] load .dockerignore => [1/4] FROM docker.io/library/python:3.11-slim => [2/4] WORKDIR /app => [3/4] COPY requirements.txt . => [4/4] RUN pip install --no-cache-dir -r requirements.txt => [5/5] COPY . . => exporting to image => => naming to docker.io/library/my-python-app
requirements.txt separately before copying the rest of the code? Docker caches each step. If you change your Python code but not your requirements, Docker reuses the cached installation step, saving massive amounts of build time.3. The Docker Build Workflow Visualized
When you run the build command, the Docker Engine reads your Dockerfile from top to bottom, executing the instructions to bake an immutable Image. That Image can then be spun up into a live Container.
From Code to Container
The Docker Engine processes your Dockerfile instructions step-by-step, generating an immutable Image that can be deployed as a live Container anywhere.
4. Step-by-Step Execution Breakdown
When you run docker build -t my-app ., the Docker Engine goes through a very specific sequence. Understanding this sequence is the key to writing efficient Dockerfiles.
/app inside the container and navigates into it.pip install. These commands modify the container's file system, adding downloaded libraries permanently to the image layer.RUN, the CMD instruction does NOT execute during the build process. It simply saves a metadata tag saying, "When someone finally starts this container, this is the command they want to run."COPY * . if you have sensitive local files or virtual environments (like .venv/ or node_modules/) in your directory. Always create a .dockerignore file in your project root to exclude local development folders from being copied into the container.5. Hands-On Practice
The best way to understand Docker is to build images yourself. Try these exercises on your local machine.
Write a Dockerfile that starts with FROM node:18-alpine. Set the working directory to /src, copy everything into it, and set the startup command to run node index.js.
Hint: Remember to use WORKDIR before your COPY instruction.
If you are building a web API, you need to tell Docker what port the app listens on. Research the EXPOSE instruction. Add it to the Python Dockerfile from Example 1 so it exposes port 8080.
Expected result: Your Dockerfile should have EXPOSE 8080 placed right before the CMD instruction.
Your current Python image is built on python:3.11-slim, which is still a few hundred megabytes. Research "Docker Multi-stage Builds". How would you use a builder stage to compile dependencies, and then copy only the finalized binaries into a bare-minimum Alpine Linux image?
Hint: A multi-stage build uses the FROM instruction twice in the same Dockerfile!
6. Interview Questions
As a software architect, I frequently ask candidates these exact questions to see if they truly understand how container engines work under the hood.
Answer: RUN executes commands during the image build process (e.g., installing software, compiling code) and commits the results as a new image layer. CMD does not execute during the build; it specifies the default command that will execute at runtime when a container is started from the built image.
Answer: It optimizes Docker's layer caching mechanism. Docker builds images layer by layer. If a layer hasn't changed, Docker reuses it from the cache. Because source code changes frequently but dependencies change rarely, copying the dependencies and running the installation step first allows Docker to cache the expensive dependency installation. If you copy everything at once, any minor code change invalidates the cache, forcing a complete reinstall of all dependencies.
Conclusion
Writing a Dockerfile is the first critical step toward mastering modern system architecture and cloud deployments. By mastering instructions like FROM, WORKDIR, COPY, RUN, and CMD, you can package any application into a portable, predictable artifact. Remember to always optimize for layer caching and keep your base images as small as possible.
Official Documentation
- Docker Documentation – Dockerfile Reference
- Docker Reference – Best practices for writing Dockerfiles
Upgradix by Shrash Studio – Learn Technology. Build Your Future.