Docker Images & Containers

Docker Images & Containers

Sufi Aurangzeb Hossain
May 9, 2025
4 min read
DockerDevOps

Docker images and containers are the foundation of Docker. Understanding how they work under the hood is crucial for mastering Docker.

Docker Images & Containers – Deep Dive

Docker images and containers are the foundation of Docker. Understanding how they work under the hood is crucial for mastering Docker.

Docker Image

  • A Docker image is a read-only template that contains everything needed to run an application: code, libraries, dependencies, environment variables, and configuration.
  • Images are built in layers and stored in the Docker registry (like Docker Hub).

Docker Container

  • A container is a running instance of an image.
  • Containers are lightweight and isolated but share the host kernel.
  • You can start, stop, move, or delete containers without affecting the base image.

Image Layers & Union File System

Each line in a Dockerfile creates a new layer. These layers are stacked using a Union File System (UFS).

  • Layers are read-only and reusable.
  • The top writable layer is where container changes (like file edits) happen.

Example Dockerfile with layers:

FROM ubuntu:20.04   # Base layer
RUN apt-get update  # Layer 2
RUN apt-get install -y python3  # Layer 3
COPY . /app         # Layer 4
CMD ["python3", "app.py"]  # Layer 5

Inspecting Images & Layers

List images:

docker images

Inspect image details:

docker inspect image_id

View image history (layers):

docker history image_id

Example: Building an Image with Layers

Create a Dockerfile for a simple Python app:

FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "app.py"]

Build and run the image:

docker build -t my-python-app .
docker run my-python-app

Difference Between Image & Container

  • Image: Blueprint (read-only).
  • Container: Running instance (read/write).

Example:

docker run -it ubuntu bash  # Creates a container from ubuntu image

Inside the container, you can install packages or edit files, but those changes won't affect the original *ubuntu* image.

Best Practices for Docker Images

  1. Use official base images – Start with *node*, *python*, *alpine*, etc.
  2. Keep images small – Use slim or alpine versions.
  3. Leverage caching – Order Dockerfile instructions carefully to reuse layers.
  4. Minimize layers – Combine commands with *&&*.
  5. Avoid unnecessary files – Use *.dockerignore* to exclude logs, node_modules, etc.
  6. Tag images properly – Use version tags instead of *latest*.

Summary

  • Docker images are built in layers and are read-only.
  • Containers are running instances of images with a writable layer.
  • Use best practices to optimize image size and performance.

In the next article, we'll cover Docker Networking – Bridge, Host, Overlay, and How Containers Communicate.