When you write dockerfile, Docker look into the instruction you write in dockerfile. Docker execute each instruction in the order you specified.
As each instruction is examined, Docker looks for an existing image in its cache that it can reuse, rather than creating a new (duplicate) image.