docker build
Command
The docker build
command is used to create a Docker image from a Dockerfile and a specified context. The context includes the Dockerfile itself and any files or directories needed during the build process. This command packages an application, its dependencies, and the environment into a single image that can be shared and deployed.
Syntax
docker build [OPTIONS] PATH | URL | -
Key Components
PATH
: Specifies the build context (directory) containing the Dockerfile and other files. It can also be a URL or-
(to read the Dockerfile from standard input).OPTIONS
: Flags that modify the behavior of the build process.
Commonly Used Options
-t, --tag
Assigns a name and optionally a tag to the resulting image.
Example:docker build -t my-app:latest .
-f, --file
Specifies the Dockerfile to use if it’s not namedDockerfile
or located in the build context.
Example:docker build -f Dockerfile.dev -t my-app:dev .
--no-cache
Prevents Docker from using the cache during the build, ensuring all instructions are re-executed.
Example:docker build --no-cache -t my-app .
--build-arg
Passes build-time arguments (ARG
) to the Dockerfile.
Example:docker build --build-arg ENV=production -t my-app .
--progress
Controls the type of progress output (auto
,plain
, ortty
).
Example:docker build --progress=plain -t my-app .
--platform
Specifies the target platform for the build (e.g.,linux/amd64
,linux/arm64
).
Example:docker build --platform linux/arm64 -t my-app .
Examples
- Basic Build
Build an image using the default Dockerfile in the current directory:docker build -t my-app .
- Using a Custom Dockerfile
Build an image using a specific Dockerfile:docker build -f custom.Dockerfile -t my-app:custom .
- Passing Build Arguments
Build an image with build-time arguments:docker build --build-arg API_KEY=12345 -t my-app .
- Disabling Cache
Force a fresh build without cache:docker build --no-cache -t my-app .
Key Features
- Layer Caching: Docker caches intermediate layers, speeding up subsequent builds when no changes are detected.
- Context: Docker sends all files in the build context to the Docker daemon. Use a
.dockerignore
file to exclude unnecessary files. - Tagged Builds: Tags make it easy to manage and version images (e.g.,
my-app:1.0
,my-app:latest
).
Building from a Remote Context
You can provide a remote Git repository or tarball as the context:
docker build https://github.com/example/repo.git#branch
Inspecting the Build Output
You can use --progress
to view detailed logs of each step in the build process.