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

  1. Ensure your Dockerfile is in the project root.
  2. Run docker build -t <name>:<tag> . to build with a tag.
  3. 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 latest for 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 RUN change.