A Dockerfile is a text document containing a series of instructions that define how to build a Docker image, automating the creation of container environments.
A Dockerfile is a fundamental component of Docker's image building system. It is a plain-text file named exactly Dockerfile (with no extension) that contains a set of instructions for assembling a Docker image. Each instruction in the Dockerfile creates a new layer in the image, specifying what base image to start from, what files to copy, what commands to run, and how the container should behave when started. The Dockerfile serves as both documentation and automation, allowing developers to version control their environment configuration and build reproducible images.
FROM: Specifies the base image to use as the starting point. Every Dockerfile must begin with a FROM instruction, except when using multi-stage builds with multiple FROM statements .
WORKDIR: Sets the working directory for any subsequent instructions, creating it if it doesn't exist. Using absolute paths is recommended for clarity .
COPY: Copies files or directories from the build context into the container filesystem .
RUN: Executes commands in a new layer on top of the current image, committing the results for use in subsequent steps .
EXPOSE: Documents which ports the container listens on at runtime, primarily serving as documentation rather than actually publishing ports .
CMD: Provides defaults for executing the container. There can only be one CMD instruction, and it can be overridden when running the container .
ENTRYPOINT: Configures a container to run as an executable, which cannot be easily overridden and works well with CMD to provide default arguments .
ENV: Sets environment variables that persist throughout the container's runtime and subsequent build steps .
ARG: Defines build-time variables that only exist during the build process, not in the final container .
To build an image from a Dockerfile, you use the docker build command, specifying the build context (usually the current directory .). Docker reads the Dockerfile, executes each instruction sequentially, and commits each result as a new layer. The build process leverages caching—if an instruction and its context haven't changed since the previous build, Docker reuses the existing layer, significantly speeding up subsequent builds. Once complete, you'll have a new image tagged with the name and version you provided.