Tips for Building Docker Images
Docker is an open-source platform that helps you build, deploy, and manage applications flexibly and efficiently across different environments. With Docker, you can package all the necessary components of an application, including source code, libraries, environment variables, and configurations, into an isolated container.
USE OFFICIAL IMAGES
With the popularity of Docker today, many software companies have their own images. Using official images helps us:
- Makes Dockerfile cleaner
- Builds are more stable (companies test before releasing)
- The resulting images are smaller (companies optimize them beforehand)
![]() | ![]() |
AVOID USING LATEST IMAGES
When software companies release new versions, they add new features and remove old ones. Therefore, if we use the “latest” images, there is a chance the system will become unstable each time the image is built.
![]() | ![]() |
CHOOSE ALPINE IMAGE
The principle of Alpine Linux is small, simple, and secure, and software companies also provide images built from Alpine Linux. Alpine images provide the necessary features for our system to run stably.
A point to note when using Alpine images is the lack of libraries. This is due to its compact size; producers only provide the most essential libraries.
Besides Alpine, Docker Images Slim or Docker Cloud are also good choices, depending on the case.
![]() | ![]() |
UTILIZE LAYER CACHING
When working with Docker, rebuilding an image happens frequently, from building an optimized image or updating obsolete libraries to releasing through a CI/CD process. To avoid wasting time by rebuilding the entire Dockerfile, Docker offers Layer Caching.
When building an image, Docker checks the previous build. If the layer has not changed, Docker will use the cache for that layer without rebuilding it. If a layer changes, Docker will rebuild it from that point onward.
With this build process, whenever there is a change in the project files, the “composer install” command must run again.
Since the composer.json and composer.lock files change less often, we can take advantage of installing packages from previous builds.
When working with layers, prioritize the build commands that change infrequently (install packages, composer, node, etc.), and place the frequently changing commands below them.
REDUCE THE NUMBER OF LAYERS
To determine the size of a Docker image, besides the installed packages, the number of layers also increases the image size. The more layers, the larger the image. There are three commands that create layers: RUN, COPY, and ADD.
The advice is to use && to combine commands into one, thereby reducing the number of layers.
![]() | ![]() |
In the example above, instead of creating 9 layers, using && reduces the number of layers. Imagine that in complex systems, reducing the number of layers will significantly reduce the image size.
CONCLUSION
![]() | Vũ Khắc Nguyễn Web Developer |