Dockerfile: Build and Configure Container Images
In this article
To build and configure Docker container images with a Dockerfile, you write a text file of instructions that Docker reads to assemble an image layer by layer, then run docker build to produce the image and docker run to launch a container from it. This article explains the full process, from writing your first Dockerfile to optimizing builds and avoiding common pitfalls.
What Is a Dockerfile and Why Use It?
A Dockerfile is a plain-text script that defines the steps to create a Docker image. Each instruction (like FROM, RUN, COPY) adds a new layer to the image, and the final image is a stack of these layers. Using a Dockerfile gives you repeatable, version-controlled builds—anyone with the file can produce the same image, which is essential for CI/CD pipelines and team collaboration. Without a Dockerfile, you would have to configure containers manually, which is error-prone and not reproducible.
Core Dockerfile Instructions
Here are the most common instructions you’ll use, in the order they typically appear:
FROM– Sets the base image (e.g.,FROM ubuntu:24.04orFROM node:20-alpine). This is always the first instruction.WORKDIR– Sets the working directory for subsequent commands (e.g.,WORKDIR /app).COPY– Copies files from your build context into the image (e.g.,COPY package.json .).RUN– Executes a command during the build (e.g.,RUN npm install). This is where you install dependencies or compile code.ENV– Sets environment variables (e.g.,ENV NODE_ENV=production).EXPOSE– Declares which port the container listens on (e.g.,EXPOSE 8080). This is documentation; it doesn’t actually publish the port.CMD– Provides the default command to run when the container starts (e.g.,CMD ["node", "server.js"]). You can override it withdocker runarguments.ENTRYPOINT– Similar toCMDbut sets the main executable that is not easily overridden. Often used together:ENTRYPOINT ["docker-entrypoint.sh"]andCMD ["--help"].
Step-by-Step: Building Your First Image
Let’s walk through a simple Node.js example. Create a directory with your app code and a Dockerfile:
- Create a file named
Dockerfilein your project root. - Write the following content:
FROM node:20-alpineWORKDIR /appCOPY package.json .RUN npm installCOPY . .EXPOSE 3000CMD ["npm", "start"] - Open a terminal in that directory and run
docker build -t my-app .The-ttags the image, and the dot is the build context (the files Docker can see). - After the build finishes, run
docker run -p 3000:3000 my-appto start a container, mapping host port 3000 to container port 3000.
You’ll see output from each build step. If a step fails, fix the error and rebuild—Docker caches layers, so only the changed step and those after it will re-run.
How to Choose a Base Image
The base image you pick affects size, security, and compatibility. Consider these factors:
- Official images (like
python,node,ubuntu) are maintained and updated regularly. Prefer them over random community images. - Alpine variants (e.g.,
node:20-alpine) are much smaller (around 5–10 MB vs. 100+ MB) but use musl libc instead of glibc, which can cause compatibility issues with some native modules. Test your app thoroughly. - Distroless images (e.g.,
gcr.io/distroless/base) contain only the runtime and no shell or package manager, improving security but making debugging harder—you can’t exec into them easily. - Specific tags like
node:20-slimare a middle ground: smaller than full, but still have a shell.
Always pin a specific version (e.g., node:20.11.1) instead of a moving tag like latest to ensure reproducible builds.
Optimizing Builds: Caching and Layer Order
Docker caches each layer after a successful build. If a step’s context hasn’t changed, Docker reuses the cached layer. To maximize cache hits:
- Copy dependency files first (like
package.json) and install dependencies before copying the rest of your source code. This way, if you only change your code, the dependency install step is cached. - Combine related
RUNcommands with&&to reduce the number of layers. For example:RUN apt-get update && apt-get install -y curl - Remove temporary files in the same
RUNcommand to avoid bloating the layer (e.g.,&& rm -rf /var/lib/apt/lists/*).
You can also use a .dockerignore file to exclude files (like node_modules or .git) from the build context, speeding up the build and preventing secrets from being copied.
Common Mistakes and How to Avoid Them
Even experienced developers hit these issues:
- Forgetting the build context – Running
docker buildfrom the wrong directory means yourCOPYcommands won’t find files. Always use the correct path or the-fflag to specify the Dockerfile location. - Using
latesttags – They change over time, breaking reproducibility. Pin versions. - Running as root – By default, containers run as root. For security, create a non-root user in your Dockerfile (e.g.,
RUN useradd -m appuserthenUSER appuser). - Exposing the wrong port –
EXPOSEis informational; you still need-por--network hostto actually publish it. - Not using
.dockerignore– You might accidentally copy secrets or large directories into the image. Add a.dockerignorewith entries likenode_modules,.git, and*.log. - Ignoring build warnings – If a
RUNcommand fails, the build fails. Read the error messages carefully; they usually tell you what’s missing.
Dockerfile vs. Other Approaches
Dockerfiles are the standard way to build images, but there are alternatives:
- Docker Compose – A YAML file that defines multi-container applications, but it still uses Dockerfiles for building individual images.
- BuildKit – The modern builder (default in recent Docker versions) that offers better caching, parallel builds, and secrets handling. You can enable it with
DOCKER_BUILDKIT=1or it’s on by default in Docker 23+. - Podman – A daemonless container engine that can build images using Dockerfiles (compatible with
docker buildcommands). - Kaniko – Builds images inside a container without a Docker daemon, useful for Kubernetes clusters.
In practice, Dockerfile remains the most portable and widely supported format.
Frequently Asked Questions
What is the difference between CMD and ENTRYPOINT?
CMD provides default arguments that can be overridden when you run the container (e.g., docker run my-image bash replaces CMD). ENTRYPOINT defines the executable that always runs; you can pass arguments to it, but you can’t replace it without the --entrypoint flag. Best practice is to use ENTRYPOINT for the main command and CMD for default flags.
How do I reduce the image size?
Start with a smaller base image like Alpine, use .dockerignore to exclude unnecessary files, combine RUN commands to reduce layers, and remove package manager caches in the same step. Multi-stage builds—where you compile in one stage and copy only the binary to a slim final stage—are the most effective technique for compiled languages like Go or Java.
Can I use environment variables in a Dockerfile?
Yes, you can set them with ENV and reference them in subsequent instructions (e.g., RUN echo $VERSION). However, you cannot use environment variables in FROM lines. For build-time variables, use ARG (e.g., ARG VERSION=1.0) and pass them with --build-arg.
Why does my build fail with "COPY failed: file not found"?
This usually means the file or directory doesn’t exist in the build context. Check that you’re running docker build from the directory that contains the file, and that your .dockerignore isn’t excluding it. Also verify the path relative to the context root (e.g., COPY ./src /app/src).
How do I debug a container that exits immediately?
Run the container with docker run -it my-image sh to get a shell (if the image has one). If it doesn’t, check the logs with docker logs <container-id> after running it detached. Also consider adding a temporary CMD ["sleep", "3600"] to keep it alive while you inspect it.
Is it safe to use root inside a container?
No, it’s a security risk. If an attacker gains access to the container, they have root privileges on the container’s filesystem and can potentially break out. Always create and switch to a non-root user in your Dockerfile using RUN useradd and USER.