Docker Images

This tutorial delves into the fundamental concepts of Docker images, their use cases, and the crucial differences between images and containers. It also provides step-by-step guides on creating, removing, and running Docker images, emphasizing practical examples with a Node.js application. Docker images play a pivotal role in modern application development and deployment, serving as encapsulated blueprints for containers that ensure consistency across various environments. Understanding Docker images is essential for achieving portability, scalability, and reproducibility in the realm of containerized applications.

What is Docker Image?

Docker images are fundamental to Docker, serving as the blueprint for containers. They contain all the necessary components to run an application, including the code, runtime, libraries, and environment variables. This makes Docker images portable and ensures consistency across different environments, as they encapsulate the application along with its dependencies.

Docker Image

Docker images are composed of layers, each representing a modification made to the image. The bottom layer is usually a base image, which could be a minimal Linux distribution or a pre-existing Docker image. Each subsequent layer represents changes to the image, such as installing new software or adding data. When a Docker container is launched from an image, it is based on the combined filesystem of all the layers.

Docker images can be created in two ways: interactively or using a Dockerfile. In the interactive method, you start with an existing Docker image, modify the environment, and save the resulting state as a new image. The Dockerfile method involves writing a text file (the Dockerfile) that specifies the steps to create the image. This method is preferred for complex images, as it allows for version control and reproducibility.

Docker images can be shared among users through the Docker Registry, which is a centralized resource for sharing and distributing Docker images. When you pull an image from the Docker Registry, you're downloading it to your local machine. Conversely, when you push an image to the Docker Registry, you're uploading it to the registry for others to use.

It's important to note the difference between Docker images and Docker containers. An image is a template for creating a container, while a container is a running instance of an image. In other words, you can think of a Docker image as a class, and a Docker container as an object of that class.

Docker Image Use Cases

Docker images have several use cases due to their versatility and efficiency. Here are some key scenarios where Docker images are beneficial:

Application Development and Testing: Docker images can be used for developing and testing applications in a controlled environment. Developers can create Docker images for their applications and execute them with Docker or another runtime, allowing them to test the application from a local development PC without execution on the host OS. This is advantageous because application testing would otherwise require setting up a dedicated testing environment.

Deployment of Applications: Docker images are a reusable asset and can be deployed on any host. Developers can take the static image layers from one project and use them in another, saving time as they do not have to recreate an image from scratch.

Reducing Infrastructure Costs: Docker images allow for efficient optimization of resources. Developer teams can consolidate resources onto a single server, thus reducing storage costs. Docker also comes with high scalability allowing you to provision required resources for a precise moment and automatically scale the infrastructure on-demand. You only pay for the resources you actually use.

Containerization Technology Adoption: Docker images are crucial in helping organizations seamlessly adopt containerization technology. Recently, Docker use cases can be seen across all industries, regardless of size and nature.

Software Development Environment Standardization: Docker images create a standardized workflow environment for every member throughout the product life cycle. More importantly, Docker is open-source and supported by a strong and vibrant community which is available to help you with any issues.

Using Official Docker Images: Docker Official Images are a curated set of Docker repositories hosted on Docker Hub. These images provide essential base repositories that serve as the starting point for the majority of users. These include operating systems such as Ubuntu and Alpine, programming languages such as Python and Node, and other essential tools such as Redis and MySQL. The images are some of the most secure images on Docker Hub.

Docker Image vs Container

The key differences between a Docker image and a Docker container are as follows:

  • Docker Image:
    • An image is a snapshot or a blueprint of a container.
    • Images are immutable, meaning once they are created, they do not change.
    • Images are used to create Docker containers.
    • Images are stored in a Docker registry such as Docker Hub.
    • A Docker image is built from a series of layers that are stacked on top of each other.
    • Images are built using a Dockerfile, which contains a list of instructions needed to create the image.
    • You can pull existing images from repositories or create your own by defining a Dockerfile and using the docker build command.
  • Docker Container:
    • A container is a running instance of an image.
    • Containers are mutable, which means they can be modified while they are running.
    • Containers run the actual applications and keep the state.
    • Containers can be started, stopped, moved, or deleted.
    • Each container has its own filesystem, networking, and isolated process space.
    • Containers are created by running an image with the docker run command.
    • A container can be thought of as the execution environment for an image.

Docker Image vs Container

In a programming analogy, if an image is a class, then a container is an instance of that class. The image provides the blueprint (the code, runtime, libraries, environment variables, etc.), and the container is the active runtime, with a writable layer that allows you to interact with the environment, make changes, and execute the application.

Containers are designed to be ephemeral and lightweight, and they run natively on the host machine's kernel, making them more efficient than virtual machines. They encapsulate an application's software environment, ensuring consistency across different development, testing, and production environments.

Prerequisites for Docker Image

Creating a Docker image involves defining a set of instructions in a Dockerfile, which is a script that contains commands and settings for building a Docker container.

Here are the basic prerequisites and steps you need to consider when creating a Docker image:

  1. Docker Installed: You must have Docker installed on your machine. For installation instructions, refer to How to install Docker.
  2. Dockerfile: A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. You need to create a Dockerfile that specifies the base image and the additional components required for your application.
  3. Base Image: You need a base image to start with, such as ubuntualpine, or a language-specific image like node:18-alpine.
  4. Application Code: The application code and any related files that need to be included in the image.
  5. Dependencies: All the dependencies required to run your application must be listed, typically in a file like package.json for Node.js applications or requirements.txt for Python applications.
  6. Docker Account: If you plan to push your image to Docker Hub, you'll need a Docker account and be logged in on your machine. You can create an account on Docker Hub.

How to Create Docker Image?

Creating a Docker image involves defining a Dockerfile that contains instructions for building the image. Let's go through a simple example using a Node.js application.

For this example, let's assume you have a basic Node.js application with the following structure:

|-- app.js
|-- package.json
|-- Dockerfile

Create Node.js Application:

Create a simple Node.js application. For example, you might have an app.js file with the following content:

// app.js
const http = require('http');

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, Docker!\\n');

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Server running on <http://localhost>:${PORT}/`);

Ensure you also have a package.json file created with npm init command.

Create Dockerfile:

Create a file named Dockerfile in the same directory as your Node.js application. This file will contain instructions for building the Docker image.

# Use an official Node.js runtime as a parent image
FROM node:14

# Set the working directory to /app

# Copy package.json and package-lock.json to the working directory
COPY package*.json ./

# Install app dependencies
RUN npm install

# Copy the current directory contents to the container at /app
COPY . .

# Make port 3000 available to the world outside this container

# Define environment variable
ENV NODE_ENV=production

# Run app.js when the container starts
CMD ["node", "app.js"]

This Dockerfile does the following:

  • Uses the official Node.js 14 image as the base image.
  • Sets the working directory to /app.
  • Copies package.json and package-lock.json to the working directory and installs dependencies.
  • Copies the application code into the container.
  • Exposes port 3000.
  • Sets the NODE_ENV environment variable to "production."
  • Specifies the command to run when the container starts (node app.js).

Build the Docker Image:

Open a terminal in the directory where your Dockerfile is located and run the following command to build the Docker image:

docker build -t docker-image-example .

This command builds Docker image and tags it with the name "docker-image-example".

Run the Docker Container:

After successfully building the image, you can run a container based on that image:

docker run -p 3000:3000 docker-image-example

This command maps port 3000 on your host machine to port 3000 on the Docker container.

Access the Application:

Open your web browser and navigate to http://localhost:3000/. You should see the "Hello, Docker!" message from your Node.js application running inside the Docker container.

This is a basic example, and you can customize the Dockerfile based on your specific application requirements.

How to Remove Docker Image?

To remove a Docker image, you can use the docker rmi command followed by the image name or image ID.

Here's a step-by-step guide on how to remove a Docker image:

  1. List Docker Images: Before removing an image, you might want to list the existing Docker images to identify the image you want to remove. Open a terminal and run:
docker images

This command will display a list of all Docker images on your system.

  1. Remove Docker Image: Once you identify the image you want to remove, use the docker rmi command. Replace <image_name> with the name of the image or <image_id> with the image ID.
docker rmi <image_name_or_id>

For example:

docker rmi docker-image-example

If the image is in use by a container, you need to stop and remove the container first before removing the image.

  1. Force Removal: If the image is in use or if there are multiple tags for the same image, you might need to force the removal. Add the f or -force option to the docker rmi command:
docker rmi -f <image_name_or_id>

For example:

docker rmi -f docker-image-example

Be cautious when using the force option, as it forcefully removes the image without checking if it's in use.

  1. Remove All Unused Images: To remove all docker images (those not associated with a running or stopped container), you can use the following command:
docker image prune

This command will prompt you to confirm the removal of unused images.

Remember to replace <image_name_or_id> with the actual name or ID of the Docker image you want to remove. Additionally, be careful when using the force option to avoid accidentally removing important images.

How to Run Docker Image?

To run a Docker image and create a container, you can use the docker run command. Here is a basic example:

docker run <image_name>

Replace <image_name> with the name or ID of the Docker image you want to run.

Here are some additional commonly used options and examples:

  1. Map Ports: If your application inside the Docker container exposes a port, you can map it to a port on your host machine using the p option:
docker run -p 8080:80 <image_name>

This example maps port 80 inside the container to port 8080 on your host machine.

2. Run in the Background: To run the container in the background (detached mode), use the d option:

docker run -d <image_name>

In detached mode, the terminal is freed up, and the container runs in the background.

  1. Interactive Mode: To run the container in interactive mode, use the it options:
docker run -it <image_name>

This is useful for interactive sessions, such as when running a shell inside the container.

  1. Assign a Name: You can assign a custom name to the container using the -name option:
docker run --name my_container <image_name>

Replace "my_container" with your desired container name.

  1. Environment Variables: If your application relies on environment variables, you can set them using the e option:
docker run -e MY_VARIABLE=value <image_name>

Replace "MY_VARIABLE" and "value" with your actual environment variable name and value.

  1. Volume Mounting: To mount a volume from your host machine into the container, use the v option:
docker run -v /path/on/host:/path/in/container <image_name>

Replace "/path/on/host" and "/path/in/container" with the paths you want to mount.


In summary, Docker images are the backbone of containerization, providing a portable and reproducible way to package applications and their dependencies. They encapsulate the runtime environment and facilitate consistent deployment across different systems. Creating a Docker image involves defining instructions in a Dockerfile, which serves as a blueprint.

Key use cases include application development, testing, deployment, and infrastructure cost reduction. Docker images standardize workflows, promoting efficient collaboration and technology adoption. They can be shared through Docker Registries for broader distribution.

Differentiating between Docker images and containers is essential; images are static blueprints, while containers are dynamic instances. Managing Docker images includes creation and removal using the docker rmi command, with options for force removal and pruning unused images. Running a Docker image to create a container involves the versatile docker run command, with options for customization.

In conclusion, Docker images play a pivotal role in modern containerization, offering efficiency, consistency, and flexibility in application deployment.

Key Takeaways

Docker Images as Blueprints: Docker images serve as blueprints for containers, encapsulating the application, code, runtime, libraries, and environment variables. They ensure consistency across different environments and facilitate portability.

Composition of Docker Images: Docker images are composed of layers, with the bottom layer being a base image. Each subsequent layer represents modifications to the image, such as installing dependencies. Images are immutable once created.

Docker Image Use Cases: Docker images find application in development, testing, deployment, cost reduction, technology adoption, and software environment standardization. They contribute to a more efficient and scalable infrastructure.

Docker Image vs Container: Understanding the distinction between Docker images and containers is crucial. An image is a blueprint, while a container is a running instance of that image. Images are immutable, and containers are mutable and can be modified while running.

Prerequisites for Docker Image: Before creating a Docker image, ensure Docker is installed, have a Dockerfile specifying the image construction steps, choose a base image, prepare application code, list dependencies, and consider using a Docker registry for sharing images.

Creating, Removing, and Running Docker Images: The process involves creating a Dockerfile, building the image using docker build, removing an image using docker rmi, and running a container with docker run. Additional options include mapping ports, running in the background, using interactive mode, assigning names, setting environment variables, and mounting volumes.

These takeaway points provide a concise summary of the key concepts and actions related to Docker images and containers.

Module 2: Working with DockerDocker Images

Top Tutorials

Related Articles

Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter