Size Matters
We've learned how to create images and we've even learned how to publish them. In this lesson, we will look at images in a bit more detail and discuss why the size of an image is important.
We'll cover the following...
When you create an image, you want it to be as small as possible for several reasons:
-
Reduce pull and push times
-
Use a minimum amount of space in the Registry
-
Use a minimum amount of space on the machines that will run the containers
-
Use a minimum amount of space on the machine that creates the image
In order to reduce the size of an image, you need to understand that it is influenced by several factors:
-
The files included in your image
-
The base image size
-
Image layers
Ideally, you want to reduce these factors. Let’s see how.
Files Included in Your Image
Include only necessary files in your image. That may sound obvious, but it’s easy to include unwanted files.
First of all, avoid COPY instructions that are too broad. A typical example that should be avoided is:
COPY . .
Try to be as precise as possible. If necessary, split them into separate COPY instructions such as:
COPY ./Project/src/*.ts ./srcCOPY ./Project/package.json .
Obviously, there are times when you will need to use COPY instructions that copy whole folders, as below:
COPY ./js/built /app/js
However, you may want to exclude files from that copy. You can use a .dockerignore file for that purpose. Simply add a .dockerignore file at the root of your build context that lists files and folders that should be excluded from the build like a .gitignore file.
Here is an example .dockerignore file:
# Ignore .git folder.git# Ignore Typescript files in any folder or subfolder**/*.ts
Second, when using package managers like NPM, NuGet, apt, and so on, make sure you run them while building the image. It will avoid sending them as the context of the image, and it will allow the layer caching system to cache the result of running them. As long as the definition file doesn’t change, Docker will reuse its cache.
Base Image Size
The base image you choose in your FROM instruction at the top of your Dockerfile file is part of the image you build.
There are optimizations in which a machine will not pull the base image when pulling your image, as long as it already pulled that base image before. But oftentimes such optimizations cannot run, so it’s better to reference small base ...