Subir archivos a "z2"
This commit is contained in:
parent
fb3c78c603
commit
afe334721c
12
z2/Dockerfile
Normal file
12
z2/Dockerfile
Normal 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"]
|
||||
137
z2/README.md
Normal file
137
z2/README.md
Normal file
@ -0,0 +1,137 @@
|
||||
# Assignment 2 - Kubernetes
|
||||
|
||||
## Application description
|
||||
This assignment demonstrates how to deploy a simple application in Kubernetes.
|
||||
|
||||
The application consists of:
|
||||
- a frontend
|
||||
- a backend
|
||||
- a PostgreSQL database
|
||||
|
||||
The frontend displays a simple web page.
|
||||
The backend provides a simple Flask service.
|
||||
The database runs in PostgreSQL with persistent storage.
|
||||
|
||||
## Kubernetes objects used
|
||||
|
||||
### Namespace
|
||||
- `z2app`
|
||||
|
||||
The namespace is used to isolate all resources of the application.
|
||||
|
||||
### Deployments
|
||||
- `frontend-deployment`
|
||||
- `backend-deployment`
|
||||
|
||||
The frontend and backend are deployed using `Deployment` because they are stateless components.
|
||||
|
||||
### StatefulSet
|
||||
- `postgres`
|
||||
|
||||
The PostgreSQL database is deployed using `StatefulSet` because it requires persistent storage.
|
||||
|
||||
### Services
|
||||
- `frontend-service`
|
||||
- `backend-service`
|
||||
- `postgres-service`
|
||||
|
||||
Services are used for communication between components and for exposing the frontend.
|
||||
|
||||
### Persistent storage
|
||||
- `PersistentVolume` (`postgres-pv`)
|
||||
- `PersistentVolumeClaim` (`postgres-pvc`)
|
||||
|
||||
These resources are used to store PostgreSQL data persistently.
|
||||
|
||||
## Container images used
|
||||
- `nginx:alpine` for frontend
|
||||
- `python:3.11-slim` for backend
|
||||
- `postgres:15` for database
|
||||
|
||||
## Application architecture
|
||||
- Frontend runs on port 80
|
||||
- Backend runs on port 5000
|
||||
- PostgreSQL runs on port 5432
|
||||
|
||||
The frontend is exposed through `frontend-service`.
|
||||
The backend is available through `backend-service`.
|
||||
The database is available through `postgres-service`.
|
||||
|
||||
## Files included
|
||||
- `deployment.yaml`
|
||||
- `service.yaml`
|
||||
- `statefulset.yaml`
|
||||
- `prepare-app.sh`
|
||||
- `start-app.sh`
|
||||
- `stop-app.sh`
|
||||
- `README.md`
|
||||
|
||||
## How to prepare the application
|
||||
|
||||
Run:
|
||||
|
||||
./prepare-app.sh
|
||||
|
||||
## How to start the application
|
||||
|
||||
Run:
|
||||
|
||||
./start-app.sh
|
||||
|
||||
## How to stop the application
|
||||
|
||||
Run:
|
||||
|
||||
./stop-app.sh
|
||||
|
||||
## How to verify that the application is running
|
||||
|
||||
# Check the pods:
|
||||
|
||||
kubectl get pods -n z2app
|
||||
|
||||
# Check the services:
|
||||
|
||||
kubectl get svc -n z2app
|
||||
|
||||
# Check persistent storage:
|
||||
|
||||
kubectl get pv
|
||||
kubectl get pvc -n z2app
|
||||
|
||||
## How to access the frontend
|
||||
|
||||
# Use port-forward:
|
||||
|
||||
kubectl port-forward -n z2app service/frontend-service 8080:80
|
||||
|
||||
# Then open in browser:
|
||||
|
||||
http://localhost:8080
|
||||
|
||||
## How to access the backend
|
||||
|
||||
# Use port-forward:
|
||||
|
||||
kubectl port-forward -n z2app service/backend-service 5000:5000
|
||||
|
||||
# Then test:
|
||||
|
||||
curl http://localhost:5000
|
||||
curl http://localhost:5000/health
|
||||
|
||||
## Notes
|
||||
|
||||
When the application starts, pods may first appear as ContainerCreating or Pending.
|
||||
After a few seconds they should become Running.
|
||||
|
||||
## Summary
|
||||
|
||||
This assignment shows how to deploy a multi-component application in Kubernetes using:
|
||||
|
||||
# Namespace
|
||||
# Deployment
|
||||
# StatefulSet
|
||||
# Service
|
||||
# PersistentVolume
|
||||
# PersistentVolumeClaim
|
||||
93
z2/app.py
Normal file
93
z2/app.py
Normal 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)
|
||||
77
z2/deployment.yaml
Normal file
77
z2/deployment.yaml
Normal file
@ -0,0 +1,77 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: backend-deployment
|
||||
namespace: z2app
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: backend
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: backend
|
||||
spec:
|
||||
containers:
|
||||
- name: backend
|
||||
image: python:3.11-slim
|
||||
command: ["/bin/sh", "-c"]
|
||||
args:
|
||||
- pip install flask psycopg2-binary && python /app/app.py
|
||||
ports:
|
||||
- containerPort: 5000
|
||||
env:
|
||||
- name: DB_HOST
|
||||
value: postgres-service
|
||||
- name: DB_PORT
|
||||
value: "5432"
|
||||
- name: DB_NAME
|
||||
value: appdb
|
||||
- name: DB_USER
|
||||
value: appuser
|
||||
- name: DB_PASSWORD
|
||||
value: apppass
|
||||
volumeMounts:
|
||||
- name: backend-code
|
||||
mountPath: /app/app.py
|
||||
subPath: app.py
|
||||
volumes:
|
||||
- name: backend-code
|
||||
configMap:
|
||||
name: backend-code-config
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: frontend-deployment
|
||||
namespace: z2app
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: frontend
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: frontend
|
||||
spec:
|
||||
containers:
|
||||
- name: frontend
|
||||
image: nginx:alpine
|
||||
ports:
|
||||
- containerPort: 80
|
||||
volumeMounts:
|
||||
- name: frontend-html
|
||||
mountPath: /usr/share/nginx/html/index.html
|
||||
subPath: index.html
|
||||
- name: frontend-nginx
|
||||
mountPath: /etc/nginx/conf.d/default.conf
|
||||
subPath: default.conf
|
||||
volumes:
|
||||
- name: frontend-html
|
||||
configMap:
|
||||
name: frontend-html-config
|
||||
- name: frontend-nginx
|
||||
configMap:
|
||||
name: frontend-nginx-config
|
||||
250
z2/index.html
Normal file
250
z2/index.html
Normal 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>
|
||||
10
z2/nginx.conf
Normal file
10
z2/nginx.conf
Normal file
@ -0,0 +1,10 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
|
||||
location / {
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
3
z2/prepare-app.sh
Normal file
3
z2/prepare-app.sh
Normal file
@ -0,0 +1,3 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
echo "No local build needed for this simplified version."
|
||||
3
z2/requirements.txt
Normal file
3
z2/requirements.txt
Normal file
@ -0,0 +1,3 @@
|
||||
flask
|
||||
psycopg2-binary
|
||||
flask-cors
|
||||
281
z2/service.yaml
Normal file
281
z2/service.yaml
Normal file
@ -0,0 +1,281 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: postgres-service
|
||||
namespace: z2app
|
||||
spec:
|
||||
selector:
|
||||
app: postgres
|
||||
ports:
|
||||
- port: 5432
|
||||
targetPort: 5432
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: backend-service
|
||||
namespace: z2app
|
||||
spec:
|
||||
selector:
|
||||
app: backend
|
||||
ports:
|
||||
- port: 5000
|
||||
targetPort: 5000
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: frontend-service
|
||||
namespace: z2app
|
||||
spec:
|
||||
type: NodePort
|
||||
selector:
|
||||
app: frontend
|
||||
ports:
|
||||
- port: 80
|
||||
targetPort: 80
|
||||
nodePort: 30080
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: frontend-html-config
|
||||
namespace: z2app
|
||||
data:
|
||||
index.html: |
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Task Notes App</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
background: #f4f6f8;
|
||||
color: #222;
|
||||
margin: 0;
|
||||
padding: 40px;
|
||||
}
|
||||
.container {
|
||||
max-width: 700px;
|
||||
margin: 0 auto;
|
||||
background: white;
|
||||
padding: 30px;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 14px rgba(0,0,0,0.1);
|
||||
}
|
||||
h1 { margin-top: 0; }
|
||||
.row {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
input {
|
||||
flex: 1;
|
||||
padding: 12px;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 8px;
|
||||
font-size: 16px;
|
||||
}
|
||||
button {
|
||||
padding: 12px 16px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
background: #2563eb;
|
||||
color: white;
|
||||
font-size: 15px;
|
||||
}
|
||||
button.delete {
|
||||
background: #dc2626;
|
||||
}
|
||||
ul {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
}
|
||||
li {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1>Task Notes App</h1>
|
||||
<p>Simple notes/tasks app running on Kubernetes.</p>
|
||||
<div class="row">
|
||||
<input id="taskInput" type="text" placeholder="Write a task or note..." />
|
||||
<button onclick="addTask()">Add</button>
|
||||
</div>
|
||||
<ul id="taskList"></ul>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
async function loadTasks() {
|
||||
const res = await fetch('/api/tasks');
|
||||
const tasks = await res.json();
|
||||
const list = document.getElementById('taskList');
|
||||
list.innerHTML = '';
|
||||
|
||||
tasks.forEach(task => {
|
||||
const li = document.createElement('li');
|
||||
li.innerHTML = `
|
||||
<span>${task.text}</span>
|
||||
<button class="delete" onclick="deleteTask(${task.id})">Delete</button>
|
||||
`;
|
||||
list.appendChild(li);
|
||||
});
|
||||
}
|
||||
|
||||
async function addTask() {
|
||||
const input = document.getElementById('taskInput');
|
||||
const text = input.value.trim();
|
||||
if (!text) return;
|
||||
|
||||
await fetch('/api/tasks', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ text })
|
||||
});
|
||||
|
||||
input.value = '';
|
||||
loadTasks();
|
||||
}
|
||||
|
||||
async function deleteTask(id) {
|
||||
await fetch('/api/tasks/' + id, { method: 'DELETE' });
|
||||
loadTasks();
|
||||
}
|
||||
|
||||
loadTasks();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: frontend-nginx-config
|
||||
namespace: z2app
|
||||
data:
|
||||
default.conf: |
|
||||
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-service:5000/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
}
|
||||
}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: backend-code-config
|
||||
namespace: z2app
|
||||
data:
|
||||
app.py: |
|
||||
import os
|
||||
import psycopg2
|
||||
from flask import Flask, request, jsonify
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
DB_HOST = os.getenv("DB_HOST", "postgres-service")
|
||||
DB_PORT = os.getenv("DB_PORT", "5432")
|
||||
DB_NAME = os.getenv("DB_NAME", "appdb")
|
||||
DB_USER = os.getenv("DB_USER", "appuser")
|
||||
DB_PASSWORD = os.getenv("DB_PASSWORD", "apppass")
|
||||
|
||||
def get_conn():
|
||||
return psycopg2.connect(
|
||||
host=DB_HOST,
|
||||
port=DB_PORT,
|
||||
dbname=DB_NAME,
|
||||
user=DB_USER,
|
||||
password=DB_PASSWORD
|
||||
)
|
||||
|
||||
def init_db():
|
||||
conn = get_conn()
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
CREATE TABLE IF NOT EXISTS tasks (
|
||||
id SERIAL PRIMARY KEY,
|
||||
text TEXT NOT NULL
|
||||
)
|
||||
""")
|
||||
conn.commit()
|
||||
cur.close()
|
||||
conn.close()
|
||||
|
||||
@app.after_request
|
||||
def add_cors_headers(response):
|
||||
response.headers["Access-Control-Allow-Origin"] = "*"
|
||||
response.headers["Access-Control-Allow-Headers"] = "Content-Type"
|
||||
response.headers["Access-Control-Allow-Methods"] = "GET,POST,DELETE,OPTIONS"
|
||||
return response
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return "Backend is running"
|
||||
|
||||
@app.route("/health")
|
||||
def health():
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.route("/tasks", methods=["GET"])
|
||||
def get_tasks():
|
||||
conn = get_conn()
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT id, text FROM tasks ORDER BY id DESC")
|
||||
rows = cur.fetchall()
|
||||
cur.close()
|
||||
conn.close()
|
||||
return jsonify([{"id": r[0], "text": r[1]} for r in rows])
|
||||
|
||||
@app.route("/tasks", methods=["POST"])
|
||||
def create_task():
|
||||
data = request.get_json()
|
||||
text = data.get("text", "").strip()
|
||||
|
||||
if not text:
|
||||
return jsonify({"error": "Text is required"}), 400
|
||||
|
||||
conn = get_conn()
|
||||
cur = conn.cursor()
|
||||
cur.execute("INSERT INTO tasks (text) VALUES (%s) RETURNING id", (text,))
|
||||
new_id = cur.fetchone()[0]
|
||||
conn.commit()
|
||||
cur.close()
|
||||
conn.close()
|
||||
|
||||
return jsonify({"id": new_id, "text": text}), 201
|
||||
|
||||
@app.route("/tasks/<int:task_id>", methods=["DELETE"])
|
||||
def delete_task(task_id):
|
||||
conn = get_conn()
|
||||
cur = conn.cursor()
|
||||
cur.execute("DELETE FROM tasks WHERE id = %s", (task_id,))
|
||||
conn.commit()
|
||||
cur.close()
|
||||
conn.close()
|
||||
return jsonify({"deleted": task_id})
|
||||
|
||||
if __name__ == "__main__":
|
||||
init_db()
|
||||
app.run(host="0.0.0.0", port=5000)
|
||||
10
z2/start-app.sh
Normal file
10
z2/start-app.sh
Normal file
@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
kubectl create namespace z2app || true
|
||||
kubectl apply -f statefulset.yaml
|
||||
kubectl apply -f deployment.yaml
|
||||
kubectl apply -f service.yaml
|
||||
|
||||
echo "Application started."
|
||||
kubectl get pods -n z2app
|
||||
59
z2/statefulset.yaml
Normal file
59
z2/statefulset.yaml
Normal file
@ -0,0 +1,59 @@
|
||||
apiVersion: v1
|
||||
kind: PersistentVolume
|
||||
metadata:
|
||||
name: postgres-pv
|
||||
spec:
|
||||
capacity:
|
||||
storage: 1Gi
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
hostPath:
|
||||
path: /tmp/postgres-data
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: postgres-pvc
|
||||
namespace: z2app
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
resources:
|
||||
requests:
|
||||
storage: 1Gi
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: postgres
|
||||
namespace: z2app
|
||||
spec:
|
||||
serviceName: postgres-service
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: postgres
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: postgres
|
||||
spec:
|
||||
containers:
|
||||
- name: postgres
|
||||
image: postgres:15
|
||||
ports:
|
||||
- containerPort: 5432
|
||||
env:
|
||||
- name: POSTGRES_DB
|
||||
value: appdb
|
||||
- name: POSTGRES_USER
|
||||
value: appuser
|
||||
- name: POSTGRES_PASSWORD
|
||||
value: apppass
|
||||
volumeMounts:
|
||||
- name: postgres-storage
|
||||
mountPath: /var/lib/postgresql/data
|
||||
volumes:
|
||||
- name: postgres-storage
|
||||
persistentVolumeClaim:
|
||||
claimName: postgres-pvc
|
||||
9
z2/stop-app.sh
Normal file
9
z2/stop-app.sh
Normal file
@ -0,0 +1,9 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
kubectl delete -f service.yaml --ignore-not-found=true
|
||||
kubectl delete -f deployment.yaml --ignore-not-found=true
|
||||
kubectl delete -f statefulset.yaml --ignore-not-found=true
|
||||
kubectl delete namespace z2app --ignore-not-found=true
|
||||
|
||||
echo "Application stopped."
|
||||
Loading…
Reference in New Issue
Block a user