Five Tips For Writing Better Dockerfiles

A simple guide to improve the clarity and performance of your Dockerfiles.

Francesco Pastore
5 min readJul 3, 2024

Docker has become a cornerstone for app deployment and a key component of any DevOps operation.

However, the importance of a well-crafted Dockerfile is sometimes underestimated, leading to potential issues and complicating support efforts.

In this article, we will explore five tips to build better Dockerfiles, enhancing both clarity and performance.

Image by Valdas Miskinis from Pixabay

1. Always chain multiple commands

Each instruction in a Dockerfile is run in its own layer built and cached independently. So, having a higher number of layers increases the complexity and performance of your builds.

As a golden rule, when creating a Dockerfile, one of the goals should be to have as few layers as possible.

For example, if you have the following Dockerfile:

FROM ubuntu

RUN apt-get update
RUN apt-get upgrade -y
RUN apt-get install -y apache2
RUN apt-get install -y apache2-utils
RUN apt-get clean

ENV APP_ENV=prod
ENV DEBUG=false

EXPOSE 80

CMD [“apache2ctl”, “-D”, “FOREGROUND”]

To increase build performance and reduce the number of layers you can rewrite the file in…

--

--

Francesco Pastore

An engineering student in Milan and a web developer for an IT company. Write about programming and cybersecurity topics.