Docker — Three Ways To Create Container Images and Their Use Cases
Creating container images with examples in different ways and their use cases
Creating efficient and small images are very important in docker. In this article, we will look at the ways to create them and their use cases
- What are Images
- What is a copy-on-write strategy?
- What are we building
- Three ways of Building Images
- Use cases
- Conclusion
What are images
The whole operating system of Linux is a filesystem. So, Images are nothing but a big tarball of a layered filesystem. If you look at the below diagram, Image is built with a bunch of immutable layers. Each layer consists of files and folders and each layer is built only with the changes corresponding to the previous layer.

The first layer is called a base layer and each layer is immutable that means once created, we can’t change the file system. It uses a copy-on-write strategy.
What is a copy-on-write strategy?
If you look at the above diagram, the base layer has three files and Layer 1 wants to change the files 2 and 3. So, it copies file2 and file3 from the base layer and writes any changes in layer 1. So, The top layer uses file2 and file3 from Layer 1 and file4 from the Layer2 instead of the base layer and layer1 respectively. But it uses file1 from base layer since there are no changes in top layers.
What are we building?
we are building a simple node js API which gives you the current time. we are using express lib for this. Let’s see how it looks from the docker images perspective.

Let’s see how we can build this image in three ways below.
Three ways of Building Images
There are three ways to create container images while working with docker. Let’s explore these methods
- Interactively building Images
- Using Dockerfile
- Importing from a tarball
Interactively building images
Step 1
As we know every image starts from the base image, we need to pull the base image node with the command docker pull node:latest

Step 2
Now we have a base image, Let’s build layers on top of this. Let’s run the container in an interactive mode with these commands.
// start a container in a detached mode
docker container run -dit --name node-express-server node//interact with the container with exec command
docker exec -it node-express-server /bin/bash
we started a container with node image in a detached mode and started in an interactive mode with exec command.
Step 3
Now we can add files, folders and build layers in the running container. Let’s create a folder called /app under usr/src and create some files.
// make a directory
mkdir /usr/src/app// cd to that directory
cd /usr/src/app//create package.json
npm init//install express
npm install --save express//install vim to edit the file on command line
apt-get update
apt-get install -y vim// create a file here and put all the content here
// i for insert, esc for command mode, : and wq! after editingvi index.js// list all the files
ls













