## Docker Workshop: From Basics to Deployment
*A Hands-on Guide for Developers*
---
## Presentation Overview
A practical introduction to Docker using a real-world **Object Detection Application** built with **Streamlit**, **YOLO**, and **OpenCV** for camera-based AI inference.
---
## Table of Contents
1. [What is Docker?](#what-is-docker)
2. [Why Use Docker?](#why-use-docker)
3. [Our Example Application](#our-example-application)
4. [Docker Basics](#docker-basics)
5. [Containerizing Our Todo App](#containerizing-our-todo-app)
6. [Database Container](#database-container)
7. [Docker Compose](#docker-compose)
8. [Hands-on Commands](#hands-on-commands)
9. [Best Practices](#best-practices)
10. [Next Steps](#next-steps)
---
## What is Docker?
Docker is a platform that uses **containerization** to package applications and their dependencies into lightweight, portable containers.
### Key Concepts:
- **Container**: A running instance of an image
- **Image**: A blueprint for creating containers
- **Dockerfile**: Instructions to build an image
- **Registry**: Storage for Docker images (like Docker Hub)
```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Application │ │ Application │ │ Application │
│ Dependencies │ │ Dependencies │ │ Dependencies │
│ OS │ │ Container │ │ Container │
│ Hardware │ │ Runtime │ │ Runtime │
└─────────────────┘ │ Host OS │ │ Host OS │
Traditional VM │ Hardware │ │ Hardware │
└─────────────────┘ └─────────────────┘
Docker Container Docker Container
```
---
## Why Use Docker?
### Problems Docker Solves:
- ❌ "It works on my machine" syndrome
- ❌ Complex environment setup
- ❌ Dependency conflicts
- ❌ Inconsistent deployments
### Benefits:
- ✅ **Portability**: Run anywhere Docker is installed
- ✅ **Consistency**: Same environment across development, testing, and production
- ✅ **Isolation**: Applications don't interfere with each other
- ✅ **Scalability**: Easy to scale up or down
- ✅ **Efficiency**: Lightweight compared to VMs
---
## Our Example Application
We'll containerize an **AI-Powered Object Detection Application** with:
### Frontend: Streamlit Web App
- Modern web-based interface
- Real-time camera access
- Interactive object detection
- Image upload capabilities
### AI Engine: YOLO + OpenCV
- YOLOv8 object detection model
- Real-time image processing
- 80+ object class detection
- Confidence scoring
### Python Ecosystem
- Streamlit for web interface
- OpenCV for image processing
- PyTorch for AI inference
- NumPy for numerical operations
### Application Architecture:
```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Web Browser │────▶│ Streamlit │────▶│ YOLO Model │
│ (Interface) │ │ (Web App) │ │ (AI Engine) │
│ │ │ │ │ │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │
▼ ▼
┌─────────────────┐ ┌─────────────────┐
│ Camera/ │ │ Object │
│ Image Input │ │ Detection │
└─────────────────┘ └─────────────────┘
```
---
## Docker Basics
### Essential Docker Commands:
#### Image Management:
```bash
# Build an image
docker build -t my-app .
# List images
docker images
# Pull an image from registry
docker pull postgres:13
# Remove an image
docker rmi my-app
```
#### Container Management:
```bash
# Run a container
docker run -d --name my-container my-app
# List running containers
docker ps
# List all containers
docker ps -a
# Stop a container
docker stop my-container
# Remove a container
docker rm my-container
# View logs
docker logs my-container
# Execute commands in running container
docker exec -it my-container bash
```
---
## Understanding the Python Application Code
Before we containerize our application, let's examine the Streamlit object detection application structure and understand how each component works.
### Project Structure
```
app/
├── streamlit_app.py # Main Streamlit application
├── requirements.txt # Python dependencies
models/ # YOLO model storage
outputs/ # Detection results storage
```
### 1. streamlit_app.py - Main Application
This is our main Streamlit application with object detection capabilities:
```python
import streamlit as st
from ultralytics import YOLO
import cv2
import numpy as np
from PIL import Image
import tempfile
import os
@st.cache_resource
def load_model():
"""Load the YOLO model once and cache it"""
try:
model = YOLO('yolov8n.pt') # Nano version for speed
return model
except Exception as e:
st.error(f"Error loading model: {e}")
return None
def detect_objects(image, model):
"""Perform object detection on an image"""
if model is None:
return None
try:
results = model(image)
return results[0] # Get first result
except Exception as e:
st.error(f"Error during detection: {e}")
return None
# Streamlit UI setup
st.title("🔍 Object Detection with YOLO")
st.write("Upload an image or use your camera to detect objects!")
```
**Key Features:**
- Streamlit web framework for interactive UI
- YOLO model integration for object detection
- Camera and image upload capabilities
- Caching for optimal performance
- Error handling for robust operation
### 2. Object Detection Logic
The core detection functionality processes images and identifies objects:
```python
def process_image_detection(uploaded_file, model):
"""Process uploaded image for object detection"""
if uploaded_file is not None:
# Load and display the image
image = Image.open(uploaded_file)
st.image(image, caption="Uploaded Image", use_column_width=True)
# Perform detection
with st.spinner("Detecting objects..."):
results = detect_objects(image, model)
if results is not None:
# Display results
annotated_image = results.plot()
st.image(annotated_image, caption="Detection Results", use_column_width=True)
# Show detection details
if len(results.boxes) > 0:
st.subheader("Detected Objects:")
for i, box in enumerate(results.boxes):
class_id = int(box.cls[0])
confidence = float(box.conf[0])
class_name = model.names[class_id]
st.write(f"**{class_name}** - Confidence: {confidence:.2%}")
else:
st.write("No objects detected in the image.")
```
**Key Features:**
- **Environment-based Configuration**: Reads database settings from environment variables
- **Connection Management**: Handles PostgreSQL connections using JDBC
- **CRUD Operations**: Create, Read, Update, Delete functionality
- **Error Handling**: Proper exception handling for database operations
- **Docker-Ready**: Automatically adapts to containerized environment
**Important Database Methods:**
1. **getAllTodos()**: Retrieves all todos from database
2. **addTodo()**: Inserts new todo with prepared statements
3. **updateTodo()**: Updates existing todo safely
4. **deleteTodo()**: Removes todo by ID
5. **toggleTodoComplete()**: Changes completion status
### 3. TodoApp.java - The GUI Application
This is the main Swing application providing the user interface:
```java
package com.todoapp;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.List;
public class TodoApp extends JFrame {
private TodoDAO todoDAO;
private DefaultListModel