Docker Image Fundamentals
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, system tools, libraries, and settings. It serves as a blueprint for creating Docker containers.
Key Characteristics of Docker Images
Immutability
Docker images are immutable, meaning once created, they cannot be changed. Any modifications require creating a new image.
graph LR
A[Dockerfile] --> B[Build Image]
B --> C[Create Container]
C --> D[Run Application]
Layered Architecture
Docker images use a layered file system, which allows efficient storage and transfer of image data.
Layer Type |
Description |
Example |
Base Layer |
Fundamental operating system |
Ubuntu 22.04 |
Dependency Layer |
System libraries and tools |
Python, Node.js |
Application Layer |
Application code and configuration |
Your custom application |
Image Creation Methods
1. Dockerfile
The most common method to create Docker images is using a Dockerfile.
## Example Dockerfile for a Python application
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y python3 python3-pip
COPY . /app
WORKDIR /app
RUN pip3 install -r requirements.txt
CMD ["python3", "app.py"]
2. Docker Commit
You can create an image from a running container using docker commit
.
## Create an image from a container
docker commit container_name new_image_name:tag
Image Naming Convention
Docker images follow a specific naming format:
repository_name/image_name:tag
- Example:
labex/python-app:latest
Image Management Commands
## List local images
docker images
## Pull an image from Docker Hub
docker pull ubuntu:22.04
## Remove an image
docker rmi image_name:tag
Best Practices
- Keep images small and focused
- Use official base images
- Minimize the number of layers
- Use multi-stage builds for complex applications
By understanding these fundamentals, you'll be well-equipped to work with Docker images effectively in your development workflow.