## ๐ 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
docker build -t myapp:latest .
-
-t: Tags the image with a name and optionally a tag (default islatest) -
.: Context path where theDockerfileresides
Specify Dockerfile Location
docker build -f path/to/Dockerfile .
Add Build Arguments
docker build --build-arg VERSION=1.2.3 -t app:1.2.3 .
- Use
ARGin Dockerfile to access this value
Build with No Cache
docker build --no-cache -t fresh-build .
- Avoids using intermediate image cache layers
Build Only Specific Targets (Multi-stage Builds)
docker build --target builder -t intermediate .
Limit Image Size (Best Practices)
-
Use minimal base images like
alpine -
Remove build dependencies after install
-
Use
.dockerignoreto reduce context
๐ Debugging Docker Builds
View Build Output Verbosely
docker build --progress=plain .
- Prints step-by-step output and environment details
Shell Access During Build (Interactive Debugging)
Use temporary steps in Dockerfile:
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
docker history myapp:latest
- See size and command of each layer
Inspect Intermediate Images
- Enable buildkit:
DOCKER_BUILDKIT=1 docker build .
-
Add debug lines in Dockerfile with
RUN sleeporRUN echocommands -
Use
--targetto stop at a specific build stage
Use BuildKit Debugging Tools
DOCKER_BUILDKIT=1 docker build --progress=plain .
- Enables more detailed output and progress bars
Lint and Validate Dockerfile
Use external tools like:
docker run --rm -i hadolint/hadolint < Dockerfile
- Hadolint is a linter for Dockerfiles
Use Temporary Containers to Test Commands
docker run -it --rm myimage /bin/sh
๐งช Testing Images
Run Locally and Verify
docker run -it myapp:latest /bin/sh
Automated Testing with docker-compose + CI/CD
-
Define test services with health checks
-
Use
docker-compose runordocker-compose execto validate
๐ฆ Export and Share Built Images
Save and Load Images
docker save myapp:latest -o myapp.tar
docker load -i myapp.tar
Push to Registry
docker tag myapp:latest myregistry.com/myapp:latest
docker push myregistry.com/myapp:latest