Docker Image Crafting
Understanding Docker Images
Docker images are read-only templates that serve as the foundation for creating containers. They contain everything needed to run an application, including code, runtime, libraries, and system tools.
Dockerfile Basics
A Dockerfile is a text document containing instructions for building a Docker image. Each instruction creates a new layer in the image.
graph TD
A[Dockerfile] --> B[Base Image]
A --> C[Copy Application Files]
A --> D[Install Dependencies]
A --> E[Configure Environment]
A --> F[Define Startup Command]
Sample Dockerfile for a Python Application
## Use official Python runtime as base image
FROM python:3.9-slim
## Set working directory in container
WORKDIR /app
## Copy requirements file
COPY requirements.txt .
## Install required packages
RUN pip install --no-cache-dir -r requirements.txt
## Copy application code
COPY . .
## Specify port number
EXPOSE 5000
## Define command to run application
CMD ["python", "app.py"]
Image Building Strategies
Strategy |
Description |
Use Case |
Single-stage Build |
Simple, straightforward builds |
Small, uncomplicated applications |
Multi-stage Build |
Optimize image size and security |
Complex applications with build dependencies |
Multi-stage Build Example
## Stage 1: Build stage
FROM maven:3.8.1-openjdk-11 AS build
WORKDIR /app
COPY pom.xml .
COPY src ./src
RUN mvn package
## Stage 2: Runtime stage
FROM openjdk:11-jre-slim
WORKDIR /app
COPY --from=build /app/target/myapp.jar .
EXPOSE 8080
CMD ["java", "-jar", "myapp.jar"]
Building and Managing Docker Images
## Build an image
docker build -t myapp:v1 .
## List local images
docker images
## Remove an image
docker rmi myapp:v1
## Tag an image
docker tag myapp:v1 myregistry/myapp:latest
Image Optimization Techniques
- Use minimal base images
- Minimize layer count
- Leverage build cache
- Remove unnecessary files
- Use .dockerignore file
Docker Image Layers
graph TD
A[Base Image Layer] --> B[Dependency Installation Layer]
B --> C[Application Code Layer]
C --> D[Configuration Layer]
D --> E[Entrypoint Layer]