Dockerfile contains builds commands that are needed to create a Docker image.
For each build command in the Dockerfile, Docker will generate a new filesystem layer.
An image is a combination of all filesystem layers created by the build commands of the Dockerfile.
Each layer is mapped to a specific build command in the Dockerfile.
For a new created image, Docker will execute all the build commands in the Dockerfile.
When building an already created image (assuming the cache was not cleared),
Docker uses, for each command in the Dockerfile, the corresponding filesystem layer from its cache, only if:
- The command and its parent were not updated.
- The command and its parent are not generating a new filesystem layer.
If any of the above conditions are met, Docker will automatically run all build commands in the Dockerfile that are below this updated build command.
Best practices:
A build command that might create a new filesystem layer every time it's executed (e.g., update OS, library)
should be placed at the bottom of the Dockerfile.
Another option is to place, when possible, that command in a parent Dockerfile and use the generated image as a parent image for the descendant Dockerfiles.
In such case case, the parent image can be re-built only when needed.
Best practices: If possible, multiple build commands should be combined in one single build command.
Following best practices when designing Dockerfiles helps:
- speed up the creation of Docker images by leveraging the cache.
- reduce the size of Docker images.
- speed up copying/downloading Docker images by skipping layers that have already been copied/downloaded.