Docker Images & Containers
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 5Inspecting Images & Layers
List images:
docker imagesInspect image details:
docker inspect image_idView image history (layers):
docker history image_idExample: 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-appDifference Between Image & Container
- Image: Blueprint (read-only).
- Container: Running instance (read/write).
Example:
docker run -it ubuntu bash # Creates a container from ubuntu imageInside the container, you can install packages or edit files, but those changes won't affect the original *ubuntu* image.
Best Practices for Docker Images
- Use official base images – Start with *node*, *python*, *alpine*, etc.
- Keep images small – Use slim or alpine versions.
- Leverage caching – Order Dockerfile instructions carefully to reuse layers.
- Minimize layers – Combine commands with *&&*.
- Avoid unnecessary files – Use *.dockerignore* to exclude logs, node_modules, etc.
- 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.