LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
Docker

Writing Your First Dockerfile

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.

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 you will learn
  • What a Dockerfile is and how it powers modern microservices.
  • The core Dockerfile syntax: FROM, WORKDIR, COPY, RUN, and CMD.
  • 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
Important: Notice how we copy 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

Source Code + Dockerfile Docker Engine (Build Process) Docker Image (Immutable) Container (Running App)

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.

Step 1: FROM Docker downloads the requested base image (like Linux with Python pre-installed) from Docker Hub. If you already have it locally, it uses the cached version.
Step 2: WORKDIR Docker creates a directory (if it doesn't exist) named /app inside the container and navigates into it.
Step 3: COPY & RUN Docker copies your requirements, then runs pip install. These commands modify the container's file system, adding downloaded libraries permanently to the image layer.
Step 4: CMD Unlike 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."
Watch out: Never use a wildcard like 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.

Beginner Exercise 1: Node.js Base Image

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.

Intermediate Exercise 2: Exposing a Port

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.

Advanced Exercise 3: Optimization

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.

Q1. What is the fundamental difference between the RUN and CMD instructions in a Dockerfile?

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.

Q2. Why is it considered a best practice to copy requirements.txt (or package.json) separately from the rest of the application source code?

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

Upgradix by Shrash Studio – Learn Technology. Build Your Future.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.