This project demonstrates how to:
- Create a Kubernetes namespace.
- Provision a Flask app and PostgreSQL database in the namespace.
- Automatically fetch and store running pod names in the PostgreSQL database.
- Kubernetes cluster (e.g., Minikube, Kind, or a cloud-based cluster)
- Docker
- kubectl
- Python 3.x
Clone this repository to your local machine:
git clone https://github.com/your-username/kubernetes-flask-postgres.git
cd kubernetes-flask-postgresApply the Kubernetes manifests to create the namespace, pods, and services.
Create the nrp namespace:
kubectl apply -f namespace.yamlDeploy the PostgreSQL pod and service:
kubectl apply -f postgres-pod.yaml
kubectl apply -f postgres-service.yamlDeploy the Flask app pod and service:
kubectl apply -f flask-pod.yaml
kubectl apply -f flask-service.yamlGrant the Flask app permission to list pods in the nrp namespace:
kubectl apply -f pod-reader-role.yaml
kubectl apply -f pod-reader-rolebinding.yamlUse kubectl port-forward to access the Flask app locally.
Forward port 5000 from the flask-app pod to your local machine:
kubectl port-forward pod/flask-app -n nrp 5000:5000Fetch the list of running pods: You can also use Postman to test this route after port forwarding This route does not give us pods that we store in our database through store-pods..This only gives the list of running pods on our namespace..This is because we can store pods in our databse that might not even be running on our namespace...
curl http://localhost:5000/podsExpected Response:
["flask-app", "postgres-db"]Before doing this first create table:
kubectl exec -it postgres-db -n nrp -- psql -U admin -d nrp_db
CREATE TABLE pods (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
\dtStore pod names in the PostgreSQL database: You can also use postman for this
curl -X POST http://localhost:5000/store-pods -H "Content-Type: application/json" -d "{\"pod_names\": [\"flask-app\", \"postgres-db\"]}"Expected Response:
{"message": "Pod names stored successfully"}Connect to the PostgreSQL pod and query the pods table to confirm the data was stored.
kubectl exec -it postgres-db -n nrp -- psql -U admin -d nrp_dbSELECT * FROM pods;Expected Output:
id | name
----+------------
1 | flask-app
2 | postgres-db
(2 rows)