What are Docker image "layers"?

I am brand new to Docker and am trying to understand exactly what a Docker image is. Every single definition of a Docker image uses the term "layer", but does not seem to define what is meant by layer.

From the official Docker docs:

We’ve already seen that Docker images are read-only templates from which Docker containers are launched. Each image consists of a series of layers. Docker makes use of union file systems to combine these layers into a single image. Union file systems allow files and directories of separate file systems, known as branches, to be transparently overlaid, forming a single coherent file system.

So I ask, what is a layer (exactly); can someone give a few concrete examples of them? And how do these layers "snap together" to form an image?


Solution 1:

I might be late, but here's my 10 cents (complementing ashishjain's answer):

Basically, a layer, or image layer is a change on an image, or an intermediate image. Every command you specify (FROM, RUN, COPY, etc.) in your Dockerfile causes the previous image to change, thus creating a new layer. You can think of it as staging changes when you're using git: You add a file's change, then another one, then another one...

Consider the following Dockerfile:

FROM rails:onbuild
ENV RAILS_ENV production
ENTRYPOINT ["bundle", "exec", "puma"]

First, we choose a starting image: rails:onbuild, which in turn has many layers. We add another layer on top of our starting image, setting the environment variable RAILS_ENV with the ENV command. Then, we tell docker to run bundle exec puma (which boots up the rails server). That's another layer.

The concept of layers comes in handy at the time of building images. Because layers are intermediate images, if you make a change to your Dockerfile, docker will build only the layer that was changed and the ones after that. This is called layer caching.

You can read more about it here.

Solution 2:

A docker container image is created using a dockerfile. Every line in a dockerfile will create a layer. Consider the following dummy example:

FROM ubuntu             #This has its own number of layers say "X"
MAINTAINER FOO          #This is one layer 
RUN mkdir /tmp/foo      #This is one layer 
RUN apt-get install vim #This is one layer 

This will create a final image where the total number of layers will be X+3