1. Multi-Stage Builds
Compiling a project requires a set of specific tools, but those tools are not needed at runtime. To reduce the image size, you can build in stages. Build in the first stage, then carry the compiled output into the next stage to produce a smaller image.
| |
The above is a Dockerfile that compiles an image for a Go project. Many projects choose alpine as the base image. However, if the project uses certain system libraries, the base image cannot be chosen arbitrarily.
2. Building with the Cache
Docker images have a layered structure, with a maximum of 127 layers. Except for the FROM instruction, every other instruction in a Dockerfile produces a new image layer. During a build, if Docker finds that an instruction will produce a layer identical to one from before, it reuses the cached layer.
To use the cache to speed up the build, put static setup and configuration instructions early and frequently changing content late.
| |
Because the project’s source code always changes on every build, it should go as close to the bottom as possible; dependency packages do not change often, so putting them at the top makes full use of the cache.
Use the following build command to disable the cache:
| |
3. Packaging Applications with S2I
Compared with using the cache to optimize build speed, a simpler approach is to package the application with S2I, adding just one image layer.
Reference link: Building Cloud Native Applications with S2I
It does not matter if a language or framework is not supported by S2I — we can package the base environment the application needs into a base image, then build on top of it.
4. The .dockerignore File
Docker works on a C/S model: when you run a build, it sends the required files to the Docker Daemon. Some files are very large and unused by the build, and they consume transfer time. We can define a .dockerignore to ignore these files, just like .gitignore.
The .dockerignore file
.git
The Dockerfile
| |
In the example above, the COPY ignores the .git directory.
5. Saving a Container as an Image
When learning Docker, you are often taught not to make any changes inside a container. That is correct — it follows immutable infrastructure.
Besides packaging images, we also go straight into containers to debug. Sometimes, for historical reasons, the image or Dockerfile cannot be found, and the container needs to be saved as an image.
Running the docker commit command saves ContainerID as the shaowenchen/myimage:latest image.
| |
