Docker image building process

Yashod Perera
3 min readApr 18, 2020

Let’s dive into how this images are actually build from Dockerfile. Let’s take an dockerfile and go step by step.

FROM node:alpine
WORKDIR /user/app
COPY package.json .
RUN npm install
COPY . .
PORT 3000CMD ["npm", "start"]

And following are the steps arise when we build the docker file.

Step 1/6 : FROM node:alpine
alpine: Pulling from library/node
Status: Downloaded newer image for node:alpine
---> bcfeabd22749
Step 2/6 : WORKDIR /user/app
---> Running in 3a4b81250301
Removing intermediate container 3a4b81250301
---> 8985045f8548
Step 3/6 : COPY package.json .
---> 1ed815c5108a
Step 4/6 : RUN npm install
---> Running in 61bd9e07980c
Removing intermediate container 61bd9e07980c
---> fce45205d52b
Step 5/6 : COPY . .
---> 79dd365b6d97
Step 6/6 : CMD ["npm", "start"]
---> Running in a5ae55d4882a
Removing intermediate container a5ae55d4882a
---> e65809425baf
Successfully built e65809425baf
Successfully tagged yashodgayashan/myapp:latest

As you know the image have two parts containing the file system and the startup command. And for clarification let’s divide these steps one by one.

Step 1/6 : FROM node:alpine
alpine: Pulling from library/node
Status: Downloaded newer image for node:alpine
---> bcfeabd22749

In Step 1 it will take the node:alpine base image and make an image without the startup command as follows.

Step 2/6 : WORKDIR /user/app
---> Running in 3a4b81250301
Removing intermediate container 3a4b81250301

---> 8985045f8548

In second step what it does is take the previous image and make the container and run the command and then copy the file structure and update the image and remove the created container as follows.

  1. It will create a container using the previous image
  2. Run the container and take the snapshot of the container
  3. Remove the intermediate container
  4. Update and create new image

I am not going to discuss further how all the steps are executing but they all do above 4 steps.

Important : Above 4 steps are sometimes vary. As an example for the 1st step it will do only the step 4.(making an image)

All the intermediate images are saved and once you do the same order they will taken from the cache instead of doing the above 4 steps. That’s how docker image building is extremely fast when it do repetitively in the same order.

Hope this post give you basic understanding how images are created and how caching is working in docker.

If you have found this helpful please hit that 👏 and share it on social media :)

--

--

Yashod Perera

Technical Writer | Tech Enthusiast | Open source contributor