Preparation
Create a new directory where all the files would live.
Create Node.js app
1 | { |
With your new package.json
file, run npm install
. If you are using npm version 5 or later, this will generate a package-lock.json
file which will be copied to your Docker image.
Then, create a server.js
file that defines a web app using the Express.js framework:
1 | ; |
Creating a Dockerfile
1 | # use the latest LTS (long term support) version 8 of node available from the Docker Hub: |
Create a .dockerignore
file in the same directory as your Dockerfile
with following content:
1 | node_modules |
This will prevent your local modules and debug logs from being copied onto your Docker image and possibly overwriting modules installed within your image.
Building your image
Go to the directory that has your Dockerfile and run the following command to build the Docker image. The -t
flag lets you tag your image so it’s easier to find later using the docker images
command:
1 | docker build -t <your username>/node-web-app . |
Your image will now be listed by Docker:
1 | mac@HansonMac ~/Code/docker/test1 docker images |
How docker utilize layer cache
The first time we build docker image:
1 | mac@HansonMac ~/Code/docker/test1 docker build -t hansonzhao007/node-web-app . |
We see that every layer need to be rebuilt.
Then we try to rebuild it again:
1 | mac@HansonMac ~/Code/docker/test1 docker build -t hansonzhao007/node-web-app . |
We can see that for every CMD, there is a Using cache
.
What are the layers
Docker containers are building blocks for applications. Each container is an image with a readable/writeable layer on top of a bunch of read-only layers.
These layers (also called intermediate images) are generated when the commands in the Dockerfile are executed during the Docker image build.
When Docker builds the container from a Dockerfile, each step corresponds to a command run in the Dockerfile. And each layer is made up of the file generated from running that command.
For example, the layer ID for step 2 is 549d3e18b855
.
1 | mac@HansonMac ~/Code/docker/test1 docker build -t hansonzhao007/node-web-app . |
Once the image is built, you can view all the layers that make up the image with the docker history command. The “Image” column (i.e intermediate image
or layer
) shows the randomly generated UUID that correlates to that layer.
1 | mac@HansonMac ~/Code/docker/test1 docker history hansonzhao007/node-web-app |
Reference
Digging into Docker layers
Dockerizing a Node.js web app
Building Efficient Dockerfiles - Node.js