04. Dockerfile & Builds
A Dockerfile is a plain text file containing a sequence of instructions that Docker uses to build an image. It is the blueprint of your containerized application and the foundation of Infrastructure as Code (IaC) in the Docker ecosystem.
4.1 Dockerfile Fundamentals
Section titled “4.1 Dockerfile Fundamentals”Docker Build Context
Section titled “Docker Build Context”When you run a docker build command (e.g., docker build .), the path you specify (.) is the build context. The Docker CLI packages all files and folders in this directory and sends them to the Docker Daemon. Warning: If your build context contains massive files (like gigabytes of logs or node_modules), it will drastically slow down the build.
Dockerfile Syntax
Section titled “Dockerfile Syntax”The syntax is simple:
INSTRUCTION argumentsInstructions are not case-sensitive, but by convention, they are written in UPPERCASE to distinguish them from arguments.
4.2 Dockerfile Instructions
Section titled “4.2 Dockerfile Instructions”These are the core commands you will use to assemble your images layer by layer.
Sets the base image for subsequent instructions. Every valid Dockerfile must start with a FROM instruction.
FROM ubuntu:22.04Executes any command in a new layer on top of the current image and commits the results. Used for installing packages and configuring the OS.
RUN apt-get update && apt-get install -y python3Copies files or directories from the host’s build context into the container’s filesystem.
COPY package.json /app/Similar to COPY, but with two extra features: it can copy from a remote URL, and it automatically extracts local tar archives. (Best practice: use COPY unless you specifically need these features).
ADD https://example.com/file.txt /app/WORKDIR
Section titled “WORKDIR”Sets the working directory for any RUN, CMD, ENTRYPOINT, COPY, and ADD instructions that follow. If the directory doesn’t exist, Docker creates it.
WORKDIR /appSets environment variables that persist both during the build and when the container is running.
ENV PORT=8080Defines variables that users can pass at build-time (using --build-arg). These variables are not available when the container is running.
ARG VERSION=latestSets the username or UID to use when running the image. Essential for security (avoid running as root!).
USER nodeEXPOSE
Section titled “EXPOSE”Documents the ports on which a container listens at runtime. Note: This does not actually publish the port to the host; it acts as documentation for the person running the container.
EXPOSE 80VOLUME
Section titled “VOLUME”Creates a mount point with the specified name and marks it as holding externally mounted volumes.
VOLUME ["/var/log/myapp"]Provides the default execution command for the container. There can only be one CMD. If a user runs docker run image <command>, it overrides the CMD.
CMD ["node", "app.js"]ENTRYPOINT
Section titled “ENTRYPOINT”Configures a container that will run as an executable. Unlike CMD, it is very difficult to override at runtime. Arguments passed to docker run are appended to the ENTRYPOINT.
ENTRYPOINT ["python3", "main.py"]Adds metadata to an image (e.g., maintainer, version, description).
LABEL maintainer="syn606@example.com"HEALTHCHECK
Section titled “HEALTHCHECK”Tells Docker how to test the container to check that it is still working.
HEALTHCHECK --interval=30s CMD curl -f http://localhost/ || exit 1Overrides the default shell used for the shell form of commands.
SHELL ["/bin/bash", "-c"]4.3 Important Comparisons
Section titled “4.3 Important Comparisons”Docker instructions can be confusingly similar. Here is how they differ:
CMD vs ENTRYPOINT
Section titled “CMD vs ENTRYPOINT”- Use
ENTRYPOINTwhen you want your container to behave like a dedicated command-line executable. - Use
CMDto provide default arguments to theENTRYPOINT, or when you want the user to easily override the command (e.g., swappingnpm startforbash).
COPY vs ADD
Section titled “COPY vs ADD”COPYis transparent and does exactly what it says: copies local files to the image.ADDhas magic behavior (auto-extracting tars and downloading URLs). UseCOPY99% of the time for predictable builds.
ARG vs ENV
Section titled “ARG vs ENV”ARGis only available duringdocker build. (e.g., Passing a temporary access token to download a private dependency).ENVis available during the build and during the container’s runtime. (e.g., Setting a database connection string).
RUN vs CMD
Section titled “RUN vs CMD”RUNexecutes during the build phase and bakes the result into the image layer (e.g., installingcurl).CMDexecutes during the run phase when the container actually starts (e.g., starting the web server).
EXPOSE vs -p
Section titled “EXPOSE vs -p”EXPOSEin the Dockerfile is just documentation for developers. It opens nothing.-p(or--publish) in the CLI actively opens and maps a port on the host machine to the container.
4.4 Docker Build
Section titled “4.4 Docker Build”Build Context & Build Cache
Section titled “Build Context & Build Cache”When Docker builds an image, it processes the Dockerfile top-to-bottom. Docker looks for an existing layer in its cache for each instruction. If the instruction (or the files it relies on) hasn’t changed, Docker reuses the cached layer, saving immense time.
Cache Invalidation
Section titled “Cache Invalidation”If a layer’s cache is invalidated (e.g., you changed a file that a COPY instruction targets), all subsequent layers are also invalidated and must be rebuilt.
Best Practice: Put frequently changing instructions (like COPY . . of your source code) at the very bottom of your Dockerfile. Put stable instructions (like RUN apt-get install) at the top.
BuildKit
Section titled “BuildKit”Docker’s modern build engine. It allows concurrent building of independent stages, better caching, and secrets management. It is enabled by default in newer Docker versions.
4.5 .dockerignore
Section titled “4.5 .dockerignore”Purpose
Section titled “Purpose”Before the Docker CLI sends the build context to the Docker Daemon, it checks for a .dockerignore file. This file tells Docker which files and directories to exclude from the context.
Syntax
Section titled “Syntax”It uses the same syntax as .gitignore.
node_modules.git*.mdSecurity Implications
Section titled “Security Implications”Without a .dockerignore, a COPY . . command might accidentally copy sensitive files (like .env, SSH keys, or passwords) into the immutable image layer, exposing them to anyone who pulls the image.
Build Optimization
Section titled “Build Optimization”Excluding massive directories (like node_modules or .git) drastically reduces the size of the build context, massively speeding up the initial docker build process.