Useful Tips for Building Docker Images
Learn the patterns and practices to follow when writing a Dockerfile.
We'll cover the following
- Keep the Docker image small
- Sort multiline instructions
- Identify cacheable layers and combine them
- Always specify a tag
- Create a common base image
- Scan the image
- Use image layer ordering to our advantage
- Leverage multi-stage build
- Use the official Docker image as the base image
- Don’t omit LABEL and EXPOSE instructions
- Wrapping up
One of the most important tools in any developer’s toolbox is the container engine, Docker. Docker gains its well-deserved popularity because it allows packaging applications in images that can run everywhere—even on old commodity hardware—with ease. In this lesson, we look at some tips and practices that help us create better Docker images. These practices largely revolve around consistency, security, and reducing the build time and the image size.
Keep the Docker image small
One of the most important things to internalize while working with Docker is to keep the image size small. Docker images can quickly grow in size to the gigabyte range. While a 1GB Docker image on local development is insignificant in terms of space consumption, the disadvantages become apparent in CI/CD pipelines where we may need to pull a specific image several times to run jobs. While bandwidth and disk space are inexpensive, time is not. Each additional minute added to the CI time becomes consequential.
For example, every one or two minutes of additional build time that can be optimized could add up over a period of time to hours of lost time per year. If our CI pipeline runs 50 times per day, that equates to 90,000 to 180,000 lost seconds per month.
This means that a development team could be waiting for 60 seconds ✕ 50 minutes per day for feedback from CI that could be avoided:
Number of Builds Per Day | Additional Build Time | Lost Time Per Year |
50 | 60 seconds | (60 ✕ 50) ✕ 5 days ✕ 52 weeks = 216hrs/year |
Get hands-on with 1400+ tech skills courses.