Please see these pages for more information:
https://docs.docker.com/engine/reference/builder/
https://docs.docker.com/develop/develop-images/dockerfile_best-practices/
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 built image, Docker will always execute the build commands if a parent build command was changed or it generated a new filesystem layer.
Otherwise Docker will use the filesystem layer from its cache.
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
or placed in a parent Dockerfile and use the generated image as a parent image for the descendant Dockerfiles.
The parent image image can be re-built only when needed.
Best practices: If possible, multiple build commands should be combined in one single build command.