Create Docker Images Step by Step

DockerDockerBeginner
Practice Now

Introduction

This comprehensive Docker tutorial provides developers and DevOps professionals with essential knowledge about creating, managing, and understanding Docker images. By exploring image components, layer structures, and practical implementation techniques, learners will gain practical skills in containerization and application packaging.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL docker(("`Docker`")) -.-> docker/ImageOperationsGroup(["`Image Operations`"]) docker(("`Docker`")) -.-> docker/DockerfileGroup(["`Dockerfile`"]) docker/ImageOperationsGroup -.-> docker/pull("`Pull Image from Repository`") docker/ImageOperationsGroup -.-> docker/push("`Push Image to Repository`") docker/ImageOperationsGroup -.-> docker/rmi("`Remove Image`") docker/ImageOperationsGroup -.-> docker/images("`List Images`") docker/DockerfileGroup -.-> docker/build("`Build Image from Dockerfile`") subgraph Lab Skills docker/pull -.-> lab-391128{{"`Create Docker Images Step by Step`"}} docker/push -.-> lab-391128{{"`Create Docker Images Step by Step`"}} docker/rmi -.-> lab-391128{{"`Create Docker Images Step by Step`"}} docker/images -.-> lab-391128{{"`Create Docker Images Step by Step`"}} docker/build -.-> lab-391128{{"`Create Docker Images Step by Step`"}} end

Docker Images Essentials

What are Docker Images?

Docker images are read-only templates used to create containers. They contain pre-configured software environments, application code, dependencies, and runtime settings. Docker images serve as blueprints for deploying consistent and reproducible application environments across different systems.

Key Components of Docker Images

graph TD A[Docker Image] --> B[Base Layer] A --> C[Application Layer] A --> D[Configuration Layer]
Component Description Example
Base Layer Fundamental operating system Ubuntu 22.04
Application Layer Software and dependencies Python 3.9, nginx
Configuration Layer Runtime settings Environment variables

Creating a Basic Docker Image

Here's an example of creating a simple Python web application image:

## Create project directory
mkdir docker-demo
cd docker-demo

## Create Dockerfile
touch Dockerfile

## Dockerfile content
cat > Dockerfile << EOL
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y python3 python3-pip
WORKDIR /app
COPY app.py .
RUN pip3 install flask
EXPOSE 5000
CMD ["python3", "app.py"]
EOL

## Create sample Flask application
cat > app.py << EOL
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return "Docker Image Example"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
EOL

## Build Docker image
docker build -t python-web-app .

Image Layers and Storage

Docker images are composed of multiple read-only layers. Each instruction in the Dockerfile creates a new layer, enabling efficient storage and quick image creation. When an image is built, Docker caches these layers to optimize build times and reduce disk space usage.

Image Identification

Docker images are uniquely identified by:

  • Repository name
  • Tag
  • Image ID

Example: ubuntu:22.04 or python-web-app:latest

Building Docker Images

Dockerfile: The Image Creation Blueprint

Dockerfile is a text file containing instructions for building a Docker image. Each instruction creates a new layer in the image, defining the environment, dependencies, and application configuration.

graph TD A[Dockerfile] --> B[Base Image] A --> C[Install Dependencies] A --> D[Copy Application Code] A --> E[Configure Runtime]

Dockerfile Instruction Types

Instruction Purpose Example
FROM Specify base image FROM ubuntu:22.04
RUN Execute commands RUN apt-get update
COPY Copy files into image COPY app/ /application
WORKDIR Set working directory WORKDIR /app
EXPOSE Define network ports EXPOSE 8080
CMD Default container command CMD ["python", "app.py"]

Practical Docker Image Build Example

## Create project structure
mkdir -p /tmp/docker-nodejs-app
cd /tmp/docker-nodejs-app

## Create Dockerfile
cat > Dockerfile << EOL
FROM node:16-alpine
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
EOL

## Create package.json
cat > package.json << EOL
{
  "name": "nodejs-docker-app",
  "version": "1.0.0",
  "dependencies": {
    "express": "^4.17.1"
  }
}
EOL

## Create simple Express server
cat > server.js << EOL
const express = require('express');
const app = express();
const PORT = 3000;

app.get('/', (req, res) => {
  res.send('Docker Image Build Example');
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
EOL

## Build Docker image
docker build -t nodejs-web-app .

## Verify image creation
docker images

Image Build Context

The build context is the directory containing the Dockerfile and referenced files. Docker sends this entire directory to the Docker daemon during image construction, enabling comprehensive image creation.

Multi-Stage Builds

Multi-stage builds allow creating smaller, more efficient images by using multiple FROM statements in a single Dockerfile, separating build-time dependencies from runtime environments.

Image Management Techniques

Docker Image Optimization Strategies

Efficient image management involves reducing image size, minimizing layer count, and implementing best practices for image creation and storage.

graph TD A[Image Management] --> B[Size Reduction] A --> C[Layer Optimization] A --> D[Image Versioning] A --> E[Registry Management]

Image Size Reduction Techniques

Technique Description Example
Alpine Base Images Minimal Linux distribution FROM alpine:3.15
Multi-Stage Builds Separate build and runtime environments Multiple FROM statements
.dockerignore Exclude unnecessary files Prevent large file transfers

Docker Image Lifecycle Management

## List local images
docker images

## Remove unused images
docker image prune

## Tag and version images
docker tag original-image:latest myregistry/image:v1.0

## Push to Docker Registry
docker push myregistry/image:v1.0

## Pull specific image version
docker pull myregistry/image:v1.0

Advanced Image Optimization Example

## Create optimized Dockerfile
cat > Dockerfile << EOL
## Multi-stage build for Python application
FROM python:3.9-alpine AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

FROM python:3.9-alpine
WORKDIR /app
COPY --from=builder /usr/local/lib/python3.9/site-packages /usr/local/lib/python3.9/site-packages
COPY . .
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser
CMD ["python", "app.py"]
EOL

## Create requirements file
cat > requirements.txt << EOL
flask==2.1.0
gunicorn==20.1.0
EOL

## Build optimized image
docker build -t optimized-python-app:slim .

## Analyze image size
docker images | grep optimized-python-app

Docker Registry Management

Docker registries provide centralized image storage and distribution. They support versioning, access control, and efficient image sharing across development teams and environments.

Image Layer Caching

Docker caches image layers to speed up subsequent builds. Ordering Dockerfile instructions from least to most frequently changing minimizes rebuild time and optimizes image creation process.

Summary

Docker images are fundamental to modern software deployment, offering a consistent and efficient way to package applications with their dependencies. By mastering image creation techniques, understanding layer mechanics, and leveraging Dockerfile instructions, developers can streamline their development workflows and ensure reliable, portable application environments across different systems.

Other Docker Tutorials you may like