To build a Docker image, you use the docker build command with a Dockerfile, specifying the build context and optionally a tag for the resulting image.
Building a Docker image is the process of creating a portable, runnable snapshot of your application and its environment using instructions defined in a Dockerfile. The primary command is docker build, which reads the Dockerfile and executes its instructions sequentially, committing each step as a new layer in the final image. The build process requires a build context—the set of files available to the Docker daemon during the build, typically specified as the current directory ..
The -t or --tag flag assigns a name and optionally a tag to the image. Without this flag, the image receives only a unique ID, making it harder to reference later. Tags follow the format name:tag, where name can include a registry hostname and repository, and tag defaults to latest if omitted. Common tagging conventions include semantic versions (v1.2.3), Git commit SHAs (a47b2c9), or environment indicators (production).
The build context is critical—everything in the specified path (including subdirectories) is sent to the Docker daemon. For efficiency and security, include a .dockerignore file to exclude unnecessary files like node_modules, .git, or temporary files. Each instruction in the Dockerfile (FROM, RUN, COPY, etc.) creates a new layer that can be cached. Docker intelligently reuses cached layers when the instruction and its context haven't changed, dramatically speeding up subsequent builds.
--no-cache: Disables layer caching, forcing a complete rebuild of all layers. Useful when you suspect cache issues or need to ensure fresh dependencies.
--build-arg: Passes build-time variables to the Dockerfile using ARG instructions, enabling dynamic configuration like version numbers or environment settings.
--target: In multi-stage builds, stops at the specified stage instead of building all stages. This is useful for creating development vs production images.
--pull: Always attempts to pull a newer version of the base image, ensuring you're building against the latest security patches.
--platform: For multi-architecture builds, specifies the target platform (e.g., linux/amd64, linux/arm64).