Docker Tutorial: Step-by-Step Guide

Docker Tutorial

Docker Tutorial: Step-by-Step Guide

Docker is a platform that allows you to package, distribute, and run applications in lightweight, portable containers. This tutorial provides a step-by-step guide to understanding and using Docker, culminating in a concrete example of containerizing a simple web application.

Prerequisites

  • Basic knowledge of command-line operations.
  • A system with Docker installed (Docker Desktop for Windows/Mac or Docker Engine for Linux).
  • Text editor (e.g., VS Code).

Step 1: Install Docker

  1. Download Docker:
    • For Windows/Mac: Install Docker Desktop.
    • For Linux: Follow the official guide for your distribution (e.g., sudo apt-get install docker.io for Ubuntu).
  2. Verify Installation:
    docker --version

    Expected output: Docker version 20.x.x or similar.

  3. Start Docker:
    • On Windows/Mac, launch Docker Desktop.
    • On Linux, ensure the Docker daemon is running: sudo systemctl start docker.

Step 2: Understand Docker Concepts

  • Container: A lightweight, isolated environment running an application and its dependencies.
  • Image: A read-only template used to create containers (e.g., nginx image for a web server).
  • Dockerfile: A script defining how to build an image.
  • Registry: A storage for images (e.g., Docker Hub).
  • Docker Compose: A tool for defining and running multi-container applications.

Step 3: Run Your First Container

  1. Pull an Image:

    Pull the official hello-world image from Docker Hub:

    docker pull hello-world
  2. Run the Container:
    docker run hello-world

    Output: A message confirming Docker is working.

  3. List Containers:

    View all containers (including stopped ones):

    docker ps -a

Step 4: Build a Custom Image

  1. Create a Project Directory:
    mkdir my-docker-app
    cd my-docker-app
  2. Write Application Code:

    Create a simple Python web app (app.py):

    from flask import Flask
    app = Flask(__name__)
    
    @app.route('/')
    def hello():
        return 'Hello, Docker!'
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000)
    
  3. Create a Dockerfile:

    In the same directory, create Dockerfile:

    # Use official Python image
    FROM python:3.9-slim
    
    # Set working directory
    WORKDIR /app
    
    # Copy application code
    COPY . .
    
    # Install dependencies
    RUN pip install flask
    
    # Expose port
    EXPOSE 5000
    
    # Command to run the app
    CMD ["python", "app.py"]
    
  4. Build the Image:
    docker build -t my-flask-app .

    -t names the image; . specifies the build context (current directory).

  5. Run the Container:
    docker run -p 5000:5000 my-flask-app

    -p maps port 5000 on the host to 5000 in the container.

  6. Test the App:

    Open a browser and navigate to http://localhost:5000. You should see "Hello, Docker!".

Step 5: Manage Containers and Images

  1. Stop a Container:

    Find the container ID:

    docker ps

    Stop it:

    docker stop <container_id>
  2. Remove a Container:
    docker rm <container_id>
  3. List Images:
    docker images
  4. Remove an Image:
    docker rmi my-flask-app

Step 6: Use Docker Compose (Optional)

For multi-container apps, Docker Compose simplifies management.

  1. Create docker-compose.yml:
    version: '3.8'
    services:
      web:
        build: .
        ports:
          - "5000:5000"
        volumes:
          - .:/app
    
  2. Run Compose:
    docker-compose up
  3. Stop Compose:
    docker-compose down

Step 7: Push to Docker Hub

  1. Log in to Docker Hub:
    docker login
  2. Tag the Image:
    docker tag my-flask-app <your_dockerhub_username>/my-flask-app:latest
  3. Push the Image:
    docker push <your_dockerhub_username>/my-flask-app:latest

Concrete Example: Deploying a Flask App

Let’s containerize a slightly more complex Flask app with a dependency.

Project Structure

my-flask-app/
├── app.py
├── requirements.txt
├── Dockerfile
└── docker-compose.yml

Files

  1. app.py:
    from flask import Flask
    import redis
    
    app = Flask(__name__)
    redis_client = redis.Redis(host='redis', port=6379)
    
    @app.route('/')
    def counter():
        count = redis_client.incr('hits')
        return f'This page has been visited {count} times!'
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000)
    
  2. requirements.txt:
    flask==2.0.1
    redis==4.0.2
    
  3. Dockerfile:
    FROM python:3.9-slim
    WORKDIR /app
    COPY requirements.txt .
    RUN pip install -r requirements.txt
    COPY . .
    EXPOSE 5000
    CMD ["python", "app.py"]
    
  4. docker-compose.yml:
    version: '3.8'
    services:
      web:
        build: .
        ports:
          - "5000:5000"
        depends_on:
          - redis
      redis:
        image: redis:6.2-alpine
    

Steps

  1. Build and Run:
    docker-compose up --build
  2. Access the App:

    Visit http://localhost:5000. Each refresh increments a counter stored in Redis.

  3. Stop the App:
    docker-compose down

Verify

  • The app should display an increasing visit count.
  • Check running containers: docker ps (shows Flask and Redis containers).

Troubleshooting

  • Port Conflict: Ensure port 5000 is free or change the host port in -p.
  • Image Build Fails: Check for typos in Dockerfile or missing dependencies.
  • Container Exits: Use docker logs <container_id> to debug.

Next Steps

  • Explore Docker volumes for persistent data.
  • Learn about Docker networking for advanced setups.
  • Experiment with Kubernetes for orchestration.

This tutorial provides a foundation for using Docker to containerize and deploy applications efficiently.

Comments

Popular posts from this blog

Building and Deploying a Recommender System on Kubeflow with KServe

CrewAI vs LangGraph: A Simple Guide to Multi-Agent Frameworks

Tutorial: Building Login and Sign-Up Pages with React, FastAPI, and XAMPP (MySQL)