The Dockerfile: A Recipe for Your Container
A Dockerfile is a text-based recipe for building a Docker image, specifying the OS, code, and dependencies. You use it to create consistent, portable application environments.
WHY IT EXISTS: To solve the classic "it works on my machine" problem. Dockerfiles provide a single, version-controllable script that defines an application's entire runtime environment. This ensures that an application and its dependencies are packaged together and run consistently everywhere, from a developer's laptop to a production server.
THE MENTAL MODEL: Think of a Dockerfile as a recipe for your application's environment. It lists all the ingredients (a base operating system image), the preparation steps (installing dependencies, copying code), and the final instruction for how to run the application. Anyone with this recipe can use the docker build command to create the exact same application image.
HOW IT WORKS: The docker build command executes the instructions in the Dockerfile sequentially. Each instruction, such as FROM, RUN, or COPY, creates a new, read-only layer in the image. Docker cleverly caches these layers. If you change a line in the Dockerfile, Docker only rebuilds that layer and the ones after it, making subsequent builds much faster. The final result is a single, cohesive image that can be used to launch containers.
WHEN TO USE IT: Use a Dockerfile for any application you intend to containerize. It's the standard for defining reproducible builds for local development, continuous integration (CI) pipelines, and deploying to container orchestrators like Kubernetes. It is a core part of modern DevOps and Infrastructure as Code (IaC) workflows.
WHEN NOT TO USE IT: A Dockerfile is overkill for simple, interactive tasks. If you just need to run a single command in a temporary environment, for example to test a script in an Ubuntu container, it's faster to use docker run ubuntu your-command directly rather than writing a Dockerfile to build a custom image for it.
ONE CANONICAL EXAMPLE: A basic Node.js Dockerfile starts with FROM node:18-alpine to use a lightweight Node.js base image. Then, WORKDIR /app sets the current directory inside the container. COPY package*.json ./ copies the dependency files, followed by RUN npm install to install them. This step is done before copying all source code so Docker can cache the installed dependencies. Next, COPY . . copies the application source code. Finally, CMD ["node", "server.js"] defines the default command to execute when a container is started from the image.
Read the original → docs.docker.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.