How to build a Docker image?
· Category: Docker
Short answer
Use docker build to create an image from a Dockerfile and a build context. The Docker client sends the context to the daemon, which executes each Dockerfile instruction sequentially and caches intermediate layers.
Steps
- Ensure your Dockerfile is in the project root.
- Run
docker build -t <name>:<tag> .to build with a tag. - Verify the image with
docker images.
Example
docker build -t myapp:v1.0 .
Build without cache for a clean build:
docker build --no-cache -t myapp:v1.0 .
Build a specific stage in a multi-stage Dockerfile:
docker build --target builder -t myapp:builder .
Tips
- Use specific tags instead of
latestfor reproducible deployments. - Pass build arguments with
--build-arg KEY=VALUE. - Use BuildKit for advanced features like secret mounts and cache exporters:
DOCKER_BUILDKIT=1 docker build -t myapp .
Common issues
- "Cannot locate specified Dockerfile" means the file path is wrong.
- Large build contexts slow down builds; use
.dockerignore. - Layer cache misses happen when files copied before
RUNchange.