DevOps Engineering Containers09 / 21

SECTION 03 · 60 MIN READ & EXPLORE

Project: Multi-Tier Application

Build, connect, trace, and verify a three-tier web application with Nginx, a Flask REST API, and PostgreSQL.

Three-Tier Container Architecture

This capstone combines everything from the Containers section into one full-stack system: an Nginx frontend (web), a Flask REST API (api), and a PostgreSQL database (db) backed by a named volume (pg_data). Notice the two distinct network paths: your browser runs on the host and reaches web and api through published localhost ports (:8001 and :5000), whereas api talks to PostgreSQL over the internal Compose network using the service hostname db:5432.

EXPLORE THE DIAGRAM

Three-tier containerized application architecture

Experiment freely. Changes disappear when you reset or refresh.

Preview of Three-tier containerized application architecture

Why and When to Separate Tiers?

Splitting frontend, API, and database into separate containers isolates failures, lets each service use its ideal base image (nginx, python, postgres), and keeps database state cleanly decoupled in a named volume.

Explore the files

docker-compose.yml

version: '3.8'

services:
  # 1. Database (PostgreSQL)
  db:
    image: postgres:16-alpine
    container_name: frmf-db
    environment:
      POSTGRES_USER: regragui
      POSTGRES_PASSWORD: tactics_secret
      POSTGRES_DB: squad_db
    volumes:
      - pg_data:/var/lib/postgresql/data
    ports:
      - "127.0.0.1:5432:5432"

  # 2. Backend API (Flask)
  api:
    build: ./backend
    container_name: frmf-api
    ports:
      - "127.0.0.1:5000:5000"
    environment:
      DATABASE_URL: postgresql://regragui:tactics_secret@db:5432/squad_db
    depends_on:
      - db

  # 3. Frontend (Nginx + Static Files)
  web:
    build: ./frontend
    container_name: frmf-web
    ports:
      - "127.0.0.1:8001:80"
    depends_on:
      - api

volumes:
  pg_data:

app.py

import os
import psycopg2
from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # Enable Cross-Origin requests so Frontend can talk to Backend

# Get DB URL from Environment Variable
DB_URL = os.getenv("DATABASE_URL", "postgresql://regragui:tactics_secret@localhost:5432/squad_db")

def get_db_connection():
    conn = psycopg2.connect(DB_URL)
    return conn

def init_db():
    """Initialize the table automatically on startup"""
    try:
        conn = get_db_connection()
        cur = conn.cursor()
        cur.execute("""
            CREATE TABLE IF NOT EXISTS players (
                id SERIAL PRIMARY KEY,
                name VARCHAR(100) NOT NULL,
                position VARCHAR(50) NOT NULL,
                number INT NOT NULL
            );
        """)
        conn.commit()
        cur.close()
        conn.close()
        print("✅ Database initialized successfully!")
    except Exception as e:
        print(f"⚠️ Database not ready yet: {e}")

# Routes
@app.route('/players', methods=['GET'])
def get_players():
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('SELECT * FROM players ORDER BY number ASC;')
    players = cur.fetchall()
    cur.close()
    conn.close()
    
    # Convert list of tuples to list of dicts
    player_list = [{"id": p[0], "name": p[1], "position": p[2], "number": p[3]} for p in players]
    return jsonify(player_list)

@app.route('/players', methods=['POST'])
def add_player():
    new_player = request.get_json()
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('INSERT INTO players (name, position, number) VALUES (%s, %s, %s)',
                (new_player['name'], new_player['position'], new_player['number']))
    conn.commit()
    cur.close()
    conn.close()
    return jsonify({"message": "Player added!"}), 201

@app.route('/players/<int:id>', methods=['DELETE'])
def delete_player(id):
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('DELETE FROM players WHERE id = %s', (id,))
    conn.commit()
    cur.close()
    conn.close()
    return jsonify({"message": "Player removed"}), 200

if __name__ == "__main__":
    # Initialize DB on start
    init_db()
    app.run(host='0.0.0.0', port=5000)

script.js

const API_URL = "http://localhost:5000/players";

async function fetchPlayers() {
    const res = await fetch(API_URL);
    const players = await res.json();
    const list = document.getElementById('squadList');
    list.innerHTML = "";
    players.forEach(p => {
        const li = document.createElement('li');
        li.innerHTML = `
            <span><b>#${p.number}</b> ${p.name} <small>(${p.position})</small></span>
            <button class="del-btn" onclick="deletePlayer(${p.id})">Remove</button>
        `;
        list.appendChild(li);
    });
}

async function addPlayer() {
    const name = document.getElementById('pName').value;
    const number = document.getElementById('pNumber').value;
    const position = document.getElementById('pPos').value;

    if(!name || !number) return alert("Please fill details");

    await fetch(API_URL, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, number, position })
    });
    
    document.getElementById('pName').value = "";
    document.getElementById('pNumber').value = "";
    fetchPlayers();
}

async function deletePlayer(id) {
    await fetch(`${API_URL}/${id}`, { method: "DELETE" });
    fetchPlayers();
}

// Load players on start
fetchPlayers();

Dockerfile

FROM python:3.11-slim

WORKDIR /app

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

COPY . .

CMD ["python", "app.py"]

Dockerfile

FROM nginx:alpine
# Copy our static files to the default Nginx public folder
COPY . /usr/share/nginx/html
SCENARIOS

Build, trace, and verify the three-tier stack

Inspect & Map the Network Paths

docker compose configDATABASE_URLAPI_URL
SITUATION

Before launching a multi-tier stack, you should know which hostnames resolve inside Docker and which ones are called by the user's browser.

TASK

Validate the Compose file and compare API_URL in frontend/script.js against DATABASE_URL in docker-compose.yml.

# Validate and inspect the full Compose configuration
docker compose config

Check two key addresses in the files above:

  • frontend/script.js calls http://localhost:5000/players because JavaScript executes inside your browser on the host, which cannot resolve Docker’s internal hostname api.
  • docker-compose.yml sets DATABASE_URL: postgresql://...@db:5432/squad_db because the Flask process runs inside the Compose network, where Docker DNS resolves db.

WHAT TO OBSERVE

You can trace both request hops: Browser -> localhost:8001 (Nginx) to load the UI, Browser -> localhost:5000 (Flask) for API calls, and Flask -> db:5432 (PostgreSQL) over the Compose bridge network.

Build & Start All Three Services

up --build -dlogs apirestart api
SITUATION

Both the frontend and backend use custom Dockerfiles, while PostgreSQL pulls postgres:16-alpine and initializes squad_db.

TASK

Build and start the entire stack in detached mode and verify all three containers are healthy.

# 1. Build custom images and start db, api, and web
docker compose up --build -d

# 2. Check container statuses and API startup logs
docker compose ps
docker compose logs api

# 3. If api started before PostgreSQL finished initializing, restart api
docker compose restart api
docker compose logs api

WHAT TO OBSERVE

docker compose ps shows frmf-db, frmf-api, and frmf-web all Up, and docker compose logs api shows Flask listening on port 5000 with no database connection errors.

Trace Live Traffic & Prove Persistence

downup -dpg_datadown -v
SITUATION

You want to verify end-to-end writes from browser to PostgreSQL and prove that player records survive a full stack restart.

TASK

Add a player in the browser, inspect the Network tab, recreate the stack without removing volumes, and confirm the player remains.

# 1. Open http://localhost:8001, add a player, and refresh the page
#    (Open browser DevTools -> Network tab to observe POST/GET calls to localhost:5000/players)

# 2. Tear down all containers and the network (retains the pg_data volume)
docker compose down

# 3. Bring the stack back up and refresh http://localhost:8001
docker compose up -d

# 4. When completely done with the project, remove containers and volume:
docker compose down --volumes

WHAT TO OBSERVE

The player created before docker compose down is still listed after docker compose up -d, proving end-to-end persistence through Nginx, Flask, PostgreSQL, and the pg_data volume.

Quick Reference

CHEAT SHEET

Troubleshooting a multi-tier Compose stack

Keep these diagnostic and recovery commands handy when debugging multi-container applications.

Inspection & Diagnostics

docker compose ps
Verify which services are Up vs. Exited
READ
docker compose logs -f api
Stream live logs for a single service
DEBUG
docker compose exec db psql
Open a shell or SQL client inside a running service
DEBUG
docker compose config
Inspect resolved ports, env vars, and volumes
READ

Recovery & Lifecycle

docker compose restart api
Restart a service after its database becomes ready
UPDATE
docker compose up --build -d
Rebuild changed Dockerfiles and recreate services
CREATE
docker compose down
Remove containers & network while keeping volumes
DELETE
docker compose down -v
Full reset: remove containers, network, and volumes
DELETE
A LITTLE CLEARER?

Take a moment to explain the idea in your own words.

Progress is saved in this browser.

DevOps Engineering

Course overview ↗

01Introduction to DevOps

  1. What is DevOps?20m
  2. DevOps Roles20m