Evaluate every instructions
If we want to optimize the build time. We need to know how much time the very instructions take. This is an example.
# Copy from: https://stackoverflow.com/a/52191994
If you want to make calculate, change
$(date +%s) will help a lot.
Leverage build cache
- In most cases, simply comparing the instruction in the Dockerfile with one of the child images is sufficient. However, certain instructions require more examination and explanation.
- For the ADD and COPY instructions, the contents of the file(s) in the image are examined and a checksum is calculated for each file. The last-modified and last-accessed times of the file(s) are not considered in these checksums.
Here are two Dockerfiles.
# do something ...
COPY requirements.txt requirements.txt
As we know, we rarely change
requirements.txt, and it may cost a lot of times during the build.
It’s proper to make it as a cached layer.
package.json(in NodeJS) and
go.mod(in Golang) should be copied before the real code is done.
Rules in Dockerfile
These rules are not mentioned in the offical document. But it help a lot to solve the problem.
Please use git tag
Some developers use
git clone in their
Dockerfile. It should not blame unless you ignore the git tag. Let me give you an example:
RUN git clone https://github.com/tornadoweb/tornado.git
It’s just work when you write the Dockerfile, btt what’s wrong with this instruction?
This instruction doesn’t specify the tornado version. It means once you change the build machine, Docker will always use the lateast tornado commit, it’s a disaster for the prodction environment.
Here is the right instruction. And you should also use version tag or something when you want to use
curl in the Dockerfile.
RUN git clone -b 'v6.0.3' https://github.com/tornadoweb/tornado.git
Simplest version for
multi-stage builds makes the docker to be suitable for
Compiled languages, such as
Please refer to Use multi-stage builds🔗,
Because an image is built during the final stage of the build process, you can minimize image layers by leveraging build cache.
- Different languages have their own building strategies to minimize the images.
- A good Dockerfile will ensure we get the almost same images even if we change the build machine.