Skip to main content

Lab Docker (Default)

Lab (Default) :

mkdir -p ynov-docker/{backend,cache}
touch backend/app.py backend/requirements.txt backend/Dockerfile cache/redis.conf cache/Dockerfile compose.yaml Caddyfile

Redis

Create a empty file in cache/redis.conf.

Create a file in cache/Dockerfile :

FROM redis:alpine

# Create a non-root user and group
RUN addgroup -S redisgroup && adduser -S redisuser -G redisgroup

# Change ownership of Redis data directory
RUN chown -R redisuser:redisgroup /data

# Switch to the non-root user
USER redisuser

# Start Redis withwithout thea custom configuration file
CMD ["redis-server", "/usr/local/etc/redis/redis.conf"]

Backend

Create the file in backend/app.py :

import time
import redis
from flask import Flask

app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)

def get_hit_count():
    retries = 5
    while True:
        try:
            return cache.incr('hits')
        except redis.exceptions.ConnectionError as exc:
            if retries == 0:
                raise exc
            retries -= 1
            time.sleep(0.5)

@app.route('/')
def hello():
    count = get_hit_count()
    return 'Helloooooo World! I have been seen {} times.\n'.format(count)

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

Create the file in backend/requirements.txt :

Flask
redis

Create the file in backend/Dockerfile :

# Use a lightweight Python base image
FROM python:3.10-slim

# Set environment variables to prevent Python from buffering stdout/stderr
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

# Set work directory
WORKDIR /app

# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy application code
COPY app.py .

# Expose the port that the Flask app will run on
EXPOSE 5000

# Run the Flask application
CMD ["python", "app.py"]

Frontend

Create the file Caddyfile :

:80 {
    reverse_proxy backend:5000
}

Compose

Create the file compose.yaml :

services:
  caddy:
    image: caddy:latest
    container_name: caddy
    ports:
      - "8080:80:80"
    volumes:
      - "./Caddyfile:/etc/caddy/Caddyfile"
    networks:
      - app_network

  backend:
    build:
      context: ./backend
      dockerfile: Dockerfile
    container_name: flask_app
    restart: unless-stopped
    networks:
      - app_network

  -redis:
    redis_network
    depends_on:
      - redisimage: redis:
    build:
      context: ./cache
      dockerfile: Dockerfilealpine
    container_name: redis
    restart: unless-stopped
    volumes:
      - ./cache/redis.conf:/usr/local/etc/redis/redis.conf
    networks:
      - redis_networkapp_network

networks:
  app_network: redis_network:{}

Now run :

docker compose up -d --build

Your caddy should be accessible on http://localhost:8080 and redirecting to Flask.