The docker build command creates a Docker image by processing a Dockerfile and the associated build context. It sends the context to the Docker daemon, which executes the Dockerfile instructions sequentially to generate a layered, immutable image of the application environment.
This article will show you how to use the docker build command to create optimized Docker images.

How Does docker build Work?
docker build reads instructions from a Dockerfile to incrementally construct a Docker image. The process starts by sending the build context (source files stored in a local directory) to the Docker daemon.
The Docker daemon reads the Dockerfile line by line, executing each instruction to build the image. The supported instructions include:
FROM. This instruction starts the build process by pulling the base image and establishing the first layer (or layers).RUN,COPY,ADD. For each of these instructions, Docker performs the following actions:- Uses the image from the previous step to spin up a temporary container.
- Executes the command or copies the files inside this container.
- Commits the result as a new, read-only image layer.
WORKDIR,ENV,CMD,EXPOSE. The instructions that only change the image configuration or metadata (not the filesystem) and do not create a new layer. Instead, they update the image's configuration file.
Note: Learn about the differences between the two frequently used Dockerfile instructions by reading Docker ADD vs. COPY.
Docker uses a build cache to speed up subsequent builds. Before executing an instruction, the daemon checks whether an existing image layer from a previous build matches the current instruction.
By strategically ordering Dockerfile instructions (placing the steps that change least frequently toward the top), the user can maximize build cache utilization.
docker build Syntax
The basic syntax for the docker build command requires specifying the build context, i.e., the location of the source code and the Dockerfile:
docker build [options] [path/url/-]
Specify the context using:
- A path. The path to a local directory containing the Dockerfile and source files.
- A URL. The URL of a Git repository or a remote compressed file.
- Standard input (stdin). Using the (
-) symbol tells Docker to read the Dockerfile from Standard Input.
The most common implementation specifies the build context path using the current directory (.):
docker build [options] .
docker build Options
Options allow for customization of the build process, including specifying the Dockerfile location, tagging the image, and passing build arguments. They control aspects such as caching, output location, and metadata.
The following is a list of the available docker build options:
-t,--tag. Names and optionally tags the image using the[name]:[tag]syntax.-f,--file. Specifies the path to an alternative Dockerfile. By default, Docker looks for a Dockerfile in the current directory.--build-arg. Sets build-time variables, accessible only during the build process, using the[key]=[value]syntax.--no-cache. Disables the build cache, forcing a complete rebuild.--platform. Sets the target platform for the build (e.g., linux/amd64).
docker build Command: Build Image from Dockerfile
Follow the steps below to create an image using a Dockerfile:
1. Create a project directory with the mkdir command:
mkdir [directory]
2. Go to the directory:
cd [directory]
3. Create a Dockerfile using a text editor such as Nano:
nano Dockerfile
4. Type the instructions into the Dockerfile. For example:
FROM python:3.9-slim-buster
WORKDIR /app
COPY . /app
EXPOSE 8000
ENV NAME World
CMD ["python", "app.py"]
5. Save the file and exit.
6. Execute the build command, tagging the resulting image. For example:
docker build -t my-app:latest .
The output shows the daemon performing the steps listed in the Dockerfile.

Note: Docker encourages users to use the docker buildx CLI plugin for all builds. In recent Docker versions, docker build is an alias for docker buildx build when BuildKit is available. However, explicit use of docker buildx build helps avoid falling back to the deprecated legacy builder.
docker build with .dockerignore
The .dockerignore file prevents unnecessary files from being sent to the Docker daemon during the build context. It is parsed before the build context is transferred.
This file uses patterns similar to .gitignore. For example:
# Ignore temporary directories and hidden files
**/.git
**/.svn
**/.hg
**/.idea
**/.vscode
# Ignore build output and dependencies that should not be copied
**/node_modules
**/vendor
**/dist
**/build
**/target
*.log
npm-debug.log*
# Ignore Docker-specific files and related documentation
Dockerfile
docker-compose.yml
README.md
# Ignore configuration files that are for development only
*.env
.env.*
docker build Command Errors and Troubleshooting
docker build errors typically fall into three main categories:
- Issues with the build context.
- Problems within a specific Dockerfile instruction.
- Resource-related failures during execution.
The sections below contain a breakdown of the most common docker build errors and their troubleshooting steps.
Build Context Issues
The problems relating to the build context are usually caused by missing or misplaced files and produce the errors listed below:
| Error | Cause | Solution |
|---|---|---|
| ERROR: Cannot locate specified Dockerfile | Docker cannot find the file named Dockerfile, or it is in a subdirectory. | Ensure the filename is Dockerfile (capital 'D', no extension). Run the command from the directory containing the file, or use the -f flag. |
| Error checking context: 'can't stat 'โฆ | A file or directory referenced in the build context is missing or has a permission issue. | Check your .dockerignore file to ensure it correctly excludes unnecessary files, especially sensitive or large ones. Verify file paths and permissions. |
| CANCELED [internal] load build context | Often relates to a large build context or network issues on platforms like Docker Desktop (especially WSL2 on Windows). | Use .dockerignore to exclude large directories like node_modules, .git, or dist. Restart your Docker daemon. |
Dockerfile Instruction Problems
Wrong or mistyped Dockerfile instructions can cause the following errors:
| Error | Cause | Solution |
|---|---|---|
| โฆ returned a non-zero code: 1 | A RUN command failed. A script, installation command, or program inside the container exited with an error. | Inspect the output directly above the error for hints (e.g., APT failed to find a package). Combine commands using && and use multi-stage builds to isolate failures. |
| COPY failed: no such file or directory | The source file specified in COPY or ADD is not in the build context. | Verify the source path is correct relative to the context directory. Remember, the build context is a local machine's directory, not the image's filesystem. |
RUN exec: "cmd": executable file not found... | The shell used by the RUN instruction (e.g., /bin/sh) cannot find the command you specified, or you are using a command (like cmd.exe) that does not exist on the Linux base image. | Ensure the program is installed in the base image. For Windows containers, commands like cmd.exe or PowerShell.exe must be explicitly available. |
Resource-Related Failures
The following errors occur due to objective resource constraints or overly strict resource limits:
| Error | Cause | Solution |
|---|---|---|
| The command '/bin/sh -c โฆ' returned a non-zero code: 137 | This code specifically indicates the container was killed by the host OS due to an Out-Of-Memory (OOM) condition. | Increase the memory limit for Docker. Optimize the Dockerfile to reduce memory usage during the build (e.g., clean up immediately after installation in the same RUN command). |
| The build step hangs indefinitely. | Often related to a missing dependency, a slow network, or an interactive command being run non-interactively. | Check for interactive commands or long-running commands. If the issue is network-related, ensure the Docker daemon's proxy settings are configured correctly. |
| Build is not picking up recent changes. | Because Docker uses a build cache to speed up image creation, it may skip a step and use an older, cached result, even if that output is now outdated. | Use docker build --no-cache . to disable the cache entirely, or structure the Dockerfile so that commands that change frequently appear after stable dependencies. |
Optimizing Docker Builds: Best Practices
Optimization focuses on minimizing image size, reducing build time, and improving security. Effective layering and proper use of multi-stage builds are critical for efficient image creation.
The following are some of the best practices worth applying when working with the docker build command:
- Use multi-stage builds. Separate build dependencies from runtime dependencies to keep the final image small.
- Minimize layers. Combine multiple related commands (e.g.,
RUN apt update && apt install -y [package]) into a singleRUNinstruction. - Place changing instructions last. Put instructions that change frequently (like
COPY . .) near the end of the Dockerfile to maximize cache utilization for stable base layers. - Leverage .dockerignore. Explicitly exclude files not needed for the build.
- Use specific base image tags. Avoid
latestand use specific version tags (e.g.,node:20-slim) for stability.
Conclusion
This guide provided instructions for using the docker build command to create Docker images. Its efficient use, complemented by best practices such as multi-stage builds and .dockerignore, is essential for generating optimized, portable container images.
Next, read how to build a Node.js app with Docker.



