Building Your Own Images (Dockerfiles)
7 min read
1. The Dockerfile Demystified: Instructions and Syntax 📄
Definition
A Dockerfile is a plain-text document containing a sequential list of instructions and commands that a user could call on the command line to assemble a Docker image.
The Problem
Before containerization, setting up a server required a tedious manual checklist. You had to install an operating system, install language runtimes, configure environment variables, copy code over FTP, and hope you didn't accidentally skip step 14. If a developer configured their local machine slightly differently than the production server, it led to the infamous "It works on my machine" syndrome.
The Concept
The Dockerfile eliminates manual setup by codifying the environment. It acts as an automated, reproducible script. Docker reads this file from top to bottom, executing each instruction to build the environment layer by layer.
Simulation: Imagine an automated car assembly line. The factory needs a precise, unskippable sequence. You cannot paint the car before the chassis is built, and you cannot install the radio before the dashboard exists. A Dockerfile provides this exact sequential blueprint to assemble your application's environment.
Syntax and Setup
A Dockerfile instruction is formatted as an INSTRUCTION followed by arguments. By convention, instructions are capitalized to distinguish them from arguments, though they are technically case-insensitive.
# syntax=docker/dockerfile:1
# This is a comment
INSTRUCTION arguments#indicates a comment.# syntax=docker/dockerfile:1is a special parser directive. According to modern Docker best practices, this should always be the very first line of your Dockerfile. It tells the Docker builder to use the latest version 1 syntax, ensuring you have the latest features, cache optimizations, and bug fixes without needing to manually upgrade your core Docker Engine.
Under the Hood
When you run the command docker build ., the Docker Engine reads the Dockerfile. Every instruction you write creates a new, read-only "layer" in the image. These layers are stacked on top of one another. If you change a line at the very bottom of the file, Docker reuses the cached layers from the top, saving massive amounts of build time.
2. Base Images and the FROM Instruction: Setting Your Foundation 🏗️
Definition
The FROM instruction initializes a new build stage and sets the Base Image for subsequent instructions. Every valid Dockerfile must start with a FROM instruction (preceded only by comments or parser directives).
The Problem
If you want to run a simple Node.js application, you need an operating system, networking utilities, and the Node runtime itself. Building all of this from absolute scratch—compiling the Linux kernel and formatting file systems—every single time you write a script would take hours and require immense system-level expertise.
The ConceptFROM allows you to stand on the shoulders of giants. Instead of building from scratch, you pull a pre-packaged image that already contains exactly what you need, and you build your app on top of it.
How it Solves the Problem (Industry Standards)
You simply declare the starting environment you want.
FROM node:18-alpineHere is how the industry handles base images:
- Use Official Images: Always pull from verified publishers on Docker Hub (e.g.,
python,node,nginx) to avoid security risks. - Pin Your Tags: The tag is the part after the colon (
18-alpine). Never use:latestin production. Usinglatestis like blindly eating a mystery-flavored jelly bean every time you deploy. Today your app builds successfully with Node 18, tomorrow Node 20 is released as "latest," and your build suddenly crashes in production due to a breaking change. Pin your versions! - Keep it Minimal: Industry veterans heavily favor
-alpineor-slimtags. An Alpine Linux base image is around 5MB. A full Ubuntu base image is over 70MB. Smaller images mean faster deployments, lower cloud storage costs, and fewer security vulnerabilities due to a dramatically smaller attack surface.
3. Executing Commands (RUN) and Copying Files (COPY/ADD) 📦
Definition
COPY: Copies files and directories from your local host machine into the container's file system.ADD: A specialized version ofCOPYthat can also extract.tarfiles automatically and fetch files from remote URLs.RUN: Executes any shell commands in a new layer on top of the current image and commits the results.
The Problem
You have your foundation (the base image), but it is completely empty of your logic. It doesn't have your application code, and it hasn't downloaded the specific third-party packages your code requires to run.
The Concept
You use COPY to bring your code into the container, and RUN to execute the necessary installation scripts (like apt-get install, npm install, or pip install).
Simulation: Think of opening a restaurant. FROM gives you the empty building with a kitchen. COPY is the delivery truck bringing in your specific secret ingredients (your code) from the warehouse. RUN is the chef actively prepping the ingredients—chopping the onions and boiling the sauce (installing dependencies)—before you open the doors to customers.
Industry Standards & Usability
COPY vs. ADD: The industry standard is to always use
COPYunless you explicitly need a local tarball auto-extracted into the image.COPYis transparent and predictable. Fetching remote packages viaADDis strongly discouraged because it leaves downloaded archives in the image, bloating the size.Chaining RUN Commands: Each
RUNinstruction creates a new layer. To keep images lean, you should chain related commands together using&&and clear caches in the same step.Industry Standard:
dockerfileRUN apt-get update && \ apt-get install -y curl && \ rm -rf /var/lib/apt/lists/*Optimize Layer Caching: Because Docker builds step-by-step, if a layer changes, all subsequent layers lose their cache and must rebuild. Therefore, you should copy your dependency files (like
package.jsonorrequirements.txt) first, run the install command, and then copy your changing application code.dockerfile# 1. Copy ONLY the dependency map first COPY package.json . # 2. Install dependencies (This layer caches perfectly unless package.json changes!) RUN npm install # 3. Copy the rest of the application code COPY . .
4. Defining Container Entry Points: CMD vs. ENTRYPOINT 🚪
Definition
Both CMD and ENTRYPOINT instructions define what process gets executed when a container starts running.
ENTRYPOINT: Configures a container that will run as a strict executable.CMD: Provides default commands and/or arguments for an executing container.
The Problem
An image is a static file system. When you spin up a container from that image, it needs to know what primary process to run. If no process is defined, the container immediately exits because it has nothing to do. Furthermore, you need a way to differentiate between a container that strictly runs a specific server vs. a container that might need to run a server or drop into a debug shell.
The ConceptENTRYPOINT is the hardcoded command that must run.CMD provides the default arguments passed to that command, which the user can easily overwrite from the terminal.
How it works & Industry Standards
Let's look at the Exec form (the industry standard syntax using JSON arrays):
Using just CMD:
CMD ["node", "server.js"]If a user runs docker run myapp, it executes node server.js. However, if a user runs docker run myapp bash, it completely ignores the CMD and runs bash instead. CMD is easily overwritten.
Using just ENTRYPOINT:
ENTRYPOINT ["node", "server.js"]If a user runs docker run myapp bash, Docker appends bash to the entrypoint, resulting in node server.js bash (which will error out). The container strictly protects its primary process.
The Industry Standard (The Combo Pattern):
The most powerful and frequent pattern in production is combining them. You use ENTRYPOINT for the fixed executable, and CMD for the default, overridable arguments.
ENTRYPOINT ["python", "app.py"]
CMD ["--port", "8080"]- Run normally:
docker run myapp➔ Executespython app.py --port 8080. - Run with override:
docker run myapp --port 9000➔ Executespython app.py --port 9000.
Under the Hood (Exec vs Shell form)
Always use the JSON array format ["command", "arg"] (Exec form) instead of plain text command arg (Shell form). If you use the Shell form, Docker wraps your command in /bin/sh -c. This wrapping breaks POSIX signal handling. When you try to stop your container gracefully, the shell intercepts the termination signal (SIGTERM) and doesn't pass it to your application, leading to ungraceful shutdowns and potentially corrupted data.
References & Extra Reading 📚
Challenge
Dockerfile Best Practices Challenge
Your task is to create a complete, production-ready Dockerfile for a hypothetical Node.js application. Your goal is to apply industry best practices for security, efficiency, and reproducibility.
Requirements:
- Syntax Directive: Start the Dockerfile with the recommended
syntaxdirective to enable modern builder features. - Base Image: Use a specific, version-pinned, and minimal official Node.js image. Choose the
alpinevariant for version18. - Working Directory: Set the working directory inside the container to
/app. - Cache Optimization: Structure your file-copying and dependency installation to leverage Docker's layer caching effectively. Copy only the necessary package definition files (
package.jsonandpackage-lock.json) first. - Efficient Dependency Installation: In a single
RUNinstruction, install the Node.js dependencies usingnpm ci(which is often preferred in production for its speed and reliability overnpm install) and then clean up the npm cache to minimize layer size. - Copy Application Code: After dependencies are installed, copy the rest of the application source code into the working directory.
- Container Startup: Configure the container's startup command. Use the
ENTRYPOINTinstruction for the executable (node) and theCMDinstruction to provide the default argument (server.js). Both must use the recommended JSON array (exec) format.
Expected result
Your Dockerfile should implement several best practices to create an optimized and secure image.
A correct solution will look similar to this:
# Use the modern Dockerfile parser
syntax=docker/dockerfile:1
# Use a specific, minimal base image
FROM node:18-alpine
# Set the working directory
WORKDIR /app
# Copy dependency definitions and install dependencies first for caching
COPY package*.json ./
RUN npm ci && npm cache clean --force
# Copy the rest of the application code
COPY . .
# Define the primary command using the preferred exec form
ENTRYPOINT ["node"]
# Provide the default, overridable argument for the entrypoint
CMD ["server.js"]Key Concepts Applied:
syntax=docker/dockerfile:1: Enables the most up-to-date Dockerfile parser features.FROM node:18-alpine: Pins a specific version (18) and uses a minimal (-alpine) base image, which enhances security and reduces image size, avoiding the unpredictable:latesttag.COPY package*.json ./followed byRUN npm ci: This is a critical cache optimization. The layer containing the installednode_moduleswill only be rebuilt ifpackage.jsonorpackage-lock.jsonchanges, not every time a source code file is modified.- Chained
RUNcommand: Combiningnpm ciandnpm cache cleaninto a singleRUNinstruction creates only one layer, resulting in a smaller final image. ENTRYPOINT ["node"]andCMD ["server.js"]: This combination creates a container that acts like an executable. It runsnode server.jsby default but allows users to easily override the script name (e.g.,docker run <image> other-script.js). The JSON array (exec) form is used to ensure proper signal handling and avoid shell-related issues.