Tabla de contenido
In Dockerfiles the order matters a lot. For example, it is not the same to execute a COPY or ADD instruction to add an executable file and then execute it than trying to execute it before adding it. This seems obvious but it is one of the main errors that cause a Dockerfile to not work correctly when trying to create an image from it.
Lighten the image by deleting files
Whenever you create an image take into account the deletion of temporary files that we will not need when running the application because this way we will save disk space. For example, if to run the application we download a compressed file, unzip its content and this content is the one we will use, we should delete the compressed file to make the image lighter.
Reduces the number of files
Avoid installing unneeded packages. If you do not do this you may have a higher memory and disk consumption with the image you are creating and you may also generate more security problems since you will have to maintain and update these files in each version.
Avoid including files that you should not by using “.dockerignore”.
Avoid including files that should not be included such as files containing personal data by using “.dockerignore” files. These files are similar to “.gitignore” files and with a few lines we can avoid filtering information.
Specifies the base image version and dependencies.
It is important to use concrete versions and not to use base images and dependencies without specifying version. Not specifying versions can lead to bugs that are not contemplated and difficult to locate.
Use the correct base image
It is important to use base images as small as possible as Alpine or Busybox whenever possible. On the other hand it is possible that with some applications we need specific images to make the application work, in this case there is not much more to comment, use it.
Finally whenever possible use official base images, doing this you will avoid problems such as using images with embedded malware.
If all the images running on your hosts are based on Ubuntu:20.04 for example, using this base image can save you more disk space than using a small image like Alpine or Busybox since you already have the other image saved on disk.