Building Docker Images
Understanding Docker Images
Docker images are read-only templates that contain everything needed to run an application: code, runtime, libraries, environment variables, and configuration files. They serve as blueprints for creating containers.
graph LR
A[Dockerfile] --> B[Docker Image]
B --> C[Docker Container]
Dockerfile Basics
A Dockerfile is a text document containing instructions for building a Docker image. Each instruction creates a new layer in the image.
Dockerfile Instruction Types
Instruction |
Purpose |
Example |
FROM |
Set base image |
FROM ubuntu:22.04 |
RUN |
Execute commands |
RUN apt-get update |
COPY |
Copy files |
COPY app.py /app/ |
WORKDIR |
Set working directory |
WORKDIR /app |
CMD |
Default command |
CMD ["python", "app.py"] |
Creating a Sample Python Application Image
Sample Project Structure
/project
├── Dockerfile
└── app.py
app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello, Docker World!"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
Dockerfile
## Use official Python runtime as base image
FROM python:3.9-slim
## Set working directory
WORKDIR /app
## Copy project files
COPY app.py requirements.txt ./
## Install dependencies
RUN pip install --no-cache-dir -r requirements.txt
## Expose port
EXPOSE 5000
## Define default command
CMD ["python", "app.py"]
Building and Managing Docker Images
## Create requirements.txt
echo "flask" > requirements.txt
## Build Docker image
docker build -t my-flask-app .
## List images
docker images
## Run container from image
docker run -p 5000:5000 my-flask-app
Image Optimization Strategies
- Use multi-stage builds
- Minimize layer count
- Leverage build cache
- Use specific image tags
- Remove unnecessary files