Assignment 1 Docker

This commit is contained in:
Pablo Pérez Arcas 2026-03-30 08:20:48 +00:00
commit 53fe5aab6d
11 changed files with 605 additions and 0 deletions

12
Dockerfile Normal file
View File

@ -0,0 +1,12 @@
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
EXPOSE 5000
CMD ["python", "app.py"]

143
README.md Normal file
View File

@ -0,0 +1,143 @@
# Assignment 1 Docker Notes App
## Overview
This project is a simple **Notes Application** built using Docker.
It demonstrates how to run a multi-container application composed of:
- Frontend (Nginx)
- Backend (Flask REST API)
- Database (PostgreSQL)
The application allows users to:
- Add notes
- View saved notes
- Delete notes
All data is stored persistently using a Docker volume.
---
## Architecture
The application consists of three services:
### 1. Frontend
- Technology: Nginx
- Serves static HTML page
- Proxies API requests to backend
- Accessible via browser
### 2. Backend
- Technology: Python (Flask)
- Provides REST API:
- `GET /api/notes`
- `POST /api/notes`
- `DELETE /api/notes/{id}`
- Connects to PostgreSQL database
### 3. Database
- Technology: PostgreSQL 16
- Stores notes data
- Uses persistent Docker volume
---
## Networking
All containers are connected via a Docker virtual network:
- **Network name:** `zkt_net`
This allows communication between:
- frontend → backend
- backend → database
---
## Persistent Storage
- **Volume name:** `zkt_db_data`
- Purpose: store PostgreSQL data
- Ensures data is not lost after stopping containers
---
## Containers Used
| Container Name | Description |
|----------------|------------------------|
| zkt_frontend | Nginx web server |
| zkt_backend | Flask API |
| zkt_db | PostgreSQL database |
---
## Requirements
- Docker
- Docker Compose (plugin)
- Linux / WSL / Docker Desktop
- Web browser
---
## How to Run the Application
### 1. Prepare the application
```bash
./prepare-app.sh
### 2. Start the application
./start-app.sh
### Then open your browser:
http://localhost:8080
### 3. Stop the application
./stop-app.sh
### 4. Remove the application
./remove-app.sh
## Testing the Application
-Open the web interface
-Add a note
-Verify it appears in the list
-Stop and restart the app:
./stop-app.sh
./start-app.sh
-Refresh the page
## If the note is still there → persistence works correctly
## Key Concepts Demonstrated
-Multi-container Docker application
-Docker Compose usage
-Container networking
-Persistent storage with volumes
-REST API communication
-Reverse proxy with Nginx
## Use of Artificial Intelligence
Artificial intelligence was used to:
-Design application architecture
-Generate initial code (frontend, backend, Docker config)
-Explain Docker concepts
-Assist with debugging and troubleshooting
-Prepare documentation
## Tool used:
-ChatGPT
-Gemini
## Pablo Pérez Arcas

93
app.py Normal file
View File

@ -0,0 +1,93 @@
from flask import Flask, request, jsonify
from flask_cors import CORS
import os
import psycopg2
import time
app = Flask(__name__)
CORS(app)
DB_HOST = os.getenv("DB_HOST", "db")
DB_NAME = os.getenv("DB_NAME", "notesdb")
DB_USER = os.getenv("DB_USER", "notesuser")
DB_PASSWORD = os.getenv("DB_PASSWORD", "notessecret")
DB_PORT = os.getenv("DB_PORT", "5432")
def get_connection():
return psycopg2.connect(
host=DB_HOST,
database=DB_NAME,
user=DB_USER,
password=DB_PASSWORD,
port=DB_PORT
)
def init_db():
for _ in range(20):
try:
conn = get_connection()
cur = conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS notes (
id SERIAL PRIMARY KEY,
content TEXT NOT NULL
);
""")
conn.commit()
cur.close()
conn.close()
return
except Exception:
time.sleep(2)
raise Exception("Database not ready")
@app.route("/api/health", methods=["GET"])
def health():
return jsonify({"status": "ok"})
@app.route("/api/notes", methods=["GET"])
def get_notes():
conn = get_connection()
cur = conn.cursor()
cur.execute("SELECT id, content FROM notes ORDER BY id DESC;")
rows = cur.fetchall()
cur.close()
conn.close()
return jsonify([{"id": r[0], "content": r[1]} for r in rows])
@app.route("/api/notes", methods=["POST"])
def add_note():
data = request.get_json()
content = data.get("content", "").strip()
if not content:
return jsonify({"error": "Content is required"}), 400
conn = get_connection()
cur = conn.cursor()
cur.execute("INSERT INTO notes (content) VALUES (%s) RETURNING id;", (content,))
note_id = cur.fetchone()[0]
conn.commit()
cur.close()
conn.close()
return jsonify({"id": note_id, "content": content}), 201
@app.route("/api/notes/<int:note_id>", methods=["DELETE"])
def delete_note(note_id):
conn = get_connection()
cur = conn.cursor()
cur.execute("DELETE FROM notes WHERE id = %s RETURNING id;", (note_id,))
deleted = cur.fetchone()
conn.commit()
cur.close()
conn.close()
if deleted is None:
return jsonify({"error": "Note not found"}), 404
return jsonify({"message": "Note deleted successfully"})
if __name__ == "__main__":
init_db()
app.run(host="0.0.0.0", port=5000)

51
docker-compose.yaml Normal file
View File

@ -0,0 +1,51 @@
services:
frontend:
image: nginx:latest
container_name: zkt_frontend
ports:
- "8080:80"
volumes:
- ./frontend/index.html:/usr/share/nginx/html/index.html:ro
- ./frontend/nginx.conf:/etc/nginx/conf.d/default.conf:ro
depends_on:
- backend
networks:
- zkt_net
restart: on-failure
backend:
build: ./backend
image: zkt-notes-backend
container_name: zkt_backend
environment:
DB_HOST: db
DB_NAME: notesdb
DB_USER: notesuser
DB_PASSWORD: notessecret
DB_PORT: "5432"
depends_on:
- db
networks:
- zkt_net
restart: on-failure
db:
image: postgres:16
container_name: zkt_db
environment:
POSTGRES_DB: notesdb
POSTGRES_USER: notesuser
POSTGRES_PASSWORD: notessecret
volumes:
- zkt_db_data:/var/lib/postgresql/data
networks:
- zkt_net
restart: on-failure
networks:
zkt_net:
external: true
volumes:
zkt_db_data:
external: true

250
index.html Normal file
View File

@ -0,0 +1,250 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Notes App</title>
<style>
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: Arial, sans-serif;
background: linear-gradient(135deg, #eef2ff, #f8fafc);
color: #1f2937;
}
.container {
max-width: 800px;
margin: 50px auto;
background: white;
padding: 30px;
border-radius: 18px;
box-shadow: 0 10px 30px rgba(0,0,0,0.08);
}
h1 {
margin-top: 0;
font-size: 42px;
}
p {
color: #4b5563;
margin-bottom: 25px;
}
.form {
display: flex;
gap: 12px;
margin-bottom: 25px;
}
input {
flex: 1;
padding: 14px;
border: 1px solid #d1d5db;
border-radius: 10px;
font-size: 16px;
}
button {
padding: 14px 18px;
border: none;
border-radius: 10px;
background: #2563eb;
color: white;
font-size: 15px;
cursor: pointer;
transition: 0.2s;
}
button:hover {
background: #1d4ed8;
}
.status {
margin-bottom: 20px;
font-size: 14px;
color: #047857;
min-height: 20px;
}
h2 {
margin-top: 10px;
font-size: 32px;
}
ul {
list-style: none;
padding: 0;
margin: 0;
}
li {
display: flex;
justify-content: space-between;
align-items: center;
background: #f9fafb;
border: 1px solid #e5e7eb;
border-radius: 12px;
padding: 14px 16px;
margin-bottom: 12px;
}
.note-text {
word-break: break-word;
padding-right: 12px;
}
.note-id {
font-size: 12px;
color: #6b7280;
margin-top: 4px;
}
.empty {
color: #6b7280;
background: #f9fafb;
border: 1px dashed #cbd5e1;
padding: 20px;
border-radius: 12px;
text-align: center;
}
.delete-btn {
background: #dc2626;
padding: 10px 14px;
font-size: 14px;
}
.delete-btn:hover {
background: #b91c1c;
}
.footer {
margin-top: 25px;
font-size: 13px;
color: #6b7280;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h1>Notes App</h1>
<p>Simple Docker project with Nginx, Flask and PostgreSQL.</p>
<div class="form">
<input id="noteInput" type="text" placeholder="Write a note..." />
<button onclick="addNote()">Add Note</button>
</div>
<div class="status" id="statusMessage"></div>
<h2>Saved notes</h2>
<ul id="notesList"></ul>
<div class="footer">
Data is stored in PostgreSQL using a persistent Docker volume.
</div>
</div>
<script>
const API_URL = "/api";
function setStatus(message, isError = false) {
const status = document.getElementById("statusMessage");
status.textContent = message;
status.style.color = isError ? "#b91c1c" : "#047857";
setTimeout(() => {
status.textContent = "";
}, 2500);
}
async function loadNotes() {
const list = document.getElementById("notesList");
try {
const res = await fetch(`${API_URL}/notes`);
const notes = await res.json();
list.innerHTML = "";
if (!notes.length) {
list.innerHTML = `<div class="empty">No notes yet. Add your first one.</div>`;
return;
}
notes.forEach(note => {
const li = document.createElement("li");
li.innerHTML = `
<div>
<div class="note-text">${escapeHtml(note.content)}</div>
<div class="note-id">Note ID: ${note.id}</div>
</div>
<button class="delete-btn" onclick="deleteNote(${note.id})">Delete</button>
`;
list.appendChild(li);
});
} catch (error) {
list.innerHTML = `<div class="empty">Could not load notes.</div>`;
}
}
async function addNote() {
const input = document.getElementById("noteInput");
const content = input.value.trim();
if (!content) {
setStatus("Please write a note first.", true);
return;
}
try {
const res = await fetch(`${API_URL}/notes`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content })
});
if (!res.ok) {
throw new Error("Failed to save note");
}
input.value = "";
setStatus("Note saved successfully.");
loadNotes();
} catch (error) {
setStatus("Could not save the note.", true);
}
}
async function deleteNote(id) {
try {
const res = await fetch(`${API_URL}/notes/${id}`, {
method: "DELETE"
});
if (!res.ok) {
throw new Error("Failed to delete note");
}
setStatus("Note deleted successfully.");
loadNotes();
} catch (error) {
setStatus("Could not delete the note.", true);
}
}
function escapeHtml(text) {
const div = document.createElement("div");
div.innerText = text;
return div.innerHTML;
}
loadNotes();
</script>
</body>
</html>

16
nginx.conf Normal file
View File

@ -0,0 +1,16 @@
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html;
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://backend:5000/api/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}

11
prepare-app.sh Normal file
View File

@ -0,0 +1,11 @@
#!/bin/bash
set -e
echo "Preparing app..."
docker network create zkt_net 2>/dev/null || true
docker volume create zkt_db_data 2>/dev/null || true
docker compose build
echo "App prepared."

10
remove-app.sh Normal file
View File

@ -0,0 +1,10 @@
#!/bin/bash
set -e
echo "Removing app..."
docker compose down
docker network rm zkt_net 2>/dev/null || true
docker volume rm zkt_db_data 2>/dev/null || true
echo "Removed app."

3
requirements.txt Normal file
View File

@ -0,0 +1,3 @@
flask
psycopg2-binary
flask-cors

8
start-app.sh Normal file
View File

@ -0,0 +1,8 @@
#!/bin/bash
set -e
echo "Running app..."
docker compose up -d
echo "The app is available at http://localhost:8080"

8
stop-app.sh Normal file
View File

@ -0,0 +1,8 @@
#!/bin/bash
set -e
echo "Stopping app..."
docker compose stop
echo "App stopped."