Docker Image Basics
What is a Docker Image?
A Docker image is a lightweight, standalone, and executable package that includes everything needed to run a piece of software, including the code, runtime, libraries, environment variables, and configuration files. It serves as a blueprint for creating Docker containers.
Key Components of Docker Images
Image Layers
Docker images are composed of multiple read-only layers that are stacked on top of each other. Each layer represents a set of filesystem changes:
graph TD
A[Base Layer: Ubuntu] --> B[Install Python]
B --> C[Copy Application Code]
C --> D[Set Environment Variables]
Image Anatomy
A typical Docker image consists of several key components:
Component |
Description |
Example |
Base Image |
Foundational layer |
Ubuntu, Alpine Linux |
Dependencies |
Required libraries and packages |
Python, Node.js |
Application Code |
Your specific application |
Flask, Django app |
Configuration |
Runtime settings |
ENV variables, Ports |
Creating Docker Images
Dockerfile
A Dockerfile is a text document containing instructions to build a Docker image. Here's a basic example:
## Use official Ubuntu base image
FROM ubuntu:22.04
## Update package lists
RUN apt-get update && apt-get upgrade -y
## Install Python
RUN apt-get install -y python3 python3-pip
## Set working directory
WORKDIR /app
## Copy application files
COPY . /app
## Install dependencies
RUN pip3 install -r requirements.txt
## Define default command
CMD ["python3", "app.py"]
Building an Image
To build a Docker image, use the docker build
command:
## Build image with a tag
docker build -t myapp:v1 .
## List available images
docker images
Image Naming and Tagging
Docker images follow a standard naming convention:
[registry]/[username]/[image-name]:[tag]
- Example:
docker.io/labex/python-app:latest
Image Storage and Distribution
Images can be stored in:
- Local Docker daemon
- Container registries (Docker Hub, LabEx Registry)
- Private repositories
Best Practices
- Use minimal base images
- Minimize layer count
- Leverage build cache
- Avoid installing unnecessary packages
- Use multi-stage builds for smaller images
By understanding these fundamentals, developers can create efficient and reproducible Docker images for their applications.