Skip to content

## ๐Ÿ“ Author

Birat Aryal โ€” birataryal.github.io
Created Date: 2025-06-18
Updated Date: Wednesday 18th June 2025 10:54:31
Website - birataryal.com.np
Repository - Birat Aryal
LinkedIn - Birat Aryal
DevSecOps Engineer | System Engineer | Cyber Security Analyst | Network Engineer

๐Ÿงช Building and Debugging Docker Images

This guide covers best practices, useful options, and techniques for building and debugging Docker images efficiently and effectively.


๐Ÿ— Building Docker Images

Basic Build Command

Bash
docker build -t myapp:latest .
  • -t: Tags the image with a name and optionally a tag (default is latest)

  • .: Context path where the Dockerfile resides

Specify Dockerfile Location

Bash
docker build -f path/to/Dockerfile .

Add Build Arguments

Bash
docker build --build-arg VERSION=1.2.3 -t app:1.2.3 .
  • Use ARG in Dockerfile to access this value

Build with No Cache

Bash
docker build --no-cache -t fresh-build .
  • Avoids using intermediate image cache layers

Build Only Specific Targets (Multi-stage Builds)

Bash
docker build --target builder -t intermediate .

Limit Image Size (Best Practices)

  • Use minimal base images like alpine

  • Remove build dependencies after install

  • Use .dockerignore to reduce context


๐Ÿž Debugging Docker Builds

View Build Output Verbosely

Bash
docker build --progress=plain .
  • Prints step-by-step output and environment details

Shell Access During Build (Interactive Debugging)

Use temporary steps in Dockerfile:

Docker
RUN echo "Debug here" && sleep 3600

Then docker exec into the container in another shell (use another build process or dev container).

Export and Analyze Image Layers

Bash
docker history myapp:latest
  • See size and command of each layer

Inspect Intermediate Images

  1. Enable buildkit:
Bash
DOCKER_BUILDKIT=1 docker build .
  1. Add debug lines in Dockerfile with RUN sleep or RUN echo commands

  2. Use --target to stop at a specific build stage

Use BuildKit Debugging Tools

Bash
DOCKER_BUILDKIT=1 docker build --progress=plain .
  • Enables more detailed output and progress bars

Lint and Validate Dockerfile

Use external tools like:

Bash
docker run --rm -i hadolint/hadolint < Dockerfile

Use Temporary Containers to Test Commands

Bash
docker run -it --rm myimage /bin/sh

๐Ÿงช Testing Images

Run Locally and Verify

Bash
docker run -it myapp:latest /bin/sh

Automated Testing with docker-compose + CI/CD

  • Define test services with health checks

  • Use docker-compose run or docker-compose exec to validate


๐Ÿ“ฆ Export and Share Built Images

Save and Load Images

Bash
docker save myapp:latest -o myapp.tar
docker load -i myapp.tar

Push to Registry

Bash
docker tag myapp:latest myregistry.com/myapp:latest
docker push myregistry.com/myapp:latest