Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 78 ยท Projects

Project: Deploy a Web App with a Database

Build a two-tier app on Kubernetes: Deployments, Services, Ingress, ConfigMap, Secret and a PersistentVolumeClaim, plus a manifest validator that catches wiring mistakes.

This is the first project of the course, and it uses the pieces you already know in one realistic setup: a web application that talks to a PostgreSQL database, reachable from outside the cluster through an Ingress. It is the shape of countless real deployments: a stateless front end, a stateful back end, configuration, a password and a way in from the internet.

Because this site has no cluster, the manifests are read-only. You read them, build them in your own cluster (for example a local kind cluster) and learn how the objects connect. The runnable parts are Python stand-ins: a validator that parses the manifests and checks every cross-reference (the mistakes that cause most first deployments to fail), and a startup simulation that shows the order in which things become ready. The application image ghcr.io/example/shop-web is a placeholder, so substitute your own.

The plan

The objects we need

Ingress Public entry: shop.example.test.
Service web Stable address for the web pods.
Deployment web Three stateless replicas.
Deployment db One PostgreSQL pod with a volume.

Plus ConfigMap, Secret and a PersistentVolumeClaim.

1 / 2
flowchart LR
  U["Browser"] --> I["Ingress<br/>shop.example.test"]
  I --> SW["Service web<br/>port 80"]
  SW --> W1["web pods x3<br/>port 8080"]
  W1 --> SD["Service db<br/>port 5432"]
  SD --> D["db pod<br/>PostgreSQL"]
  D --> V[("PVC db-data")]

Traffic enters through the Ingress, reaches the web pods through a Service, and the web pods use a second Service to find the database.

Namespace, ConfigMap and Secret

Put everything in its own namespace (namespaces and quotas). The ConfigMap holds ordinary settings and the Secret holds the password (ConfigMaps, Secrets).

YAML
apiVersion: v1
kind: Namespace
metadata:
  name: shop
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: web-config
  namespace: shop
data:
  APP_ENV: production
  DB_HOST: db
  DB_PORT: "5432"
  DB_NAME: shop
  DB_USER: shop
---
apiVersion: v1
kind: Secret
metadata:
  name: db-credentials
  namespace: shop
type: Opaque
stringData:
  POSTGRES_PASSWORD: change-me-in-real-life

Notes: DB_HOST: db works because the database Service will be named db, and Kubernetes DNS resolves it inside the namespace (DNS and discovery). DB_PORT is quoted because ConfigMap values must be strings. The Secret uses stringData for readability, and the API stores it base64-encoded, which is encoding and not encryption. In a real repository you would never commit this file with a real password; use external or sealed secrets.

The database: PVC, Deployment and Service

A claim asks for 5 GiB of storage. The cluster's default StorageClass provisions a volume for it (PersistentVolumes, StorageClasses).

YAML
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: db-data
  namespace: shop
spec:
  accessModes: ["ReadWriteOnce"]
  resources:
    requests:
      storage: 5Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: db
  namespace: shop
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: db
  template:
    metadata:
      labels:
        app: db
    spec:
      containers:
        - name: postgres
          image: postgres:17
          ports:
            - containerPort: 5432
          env:
            - name: POSTGRES_DB
              value: shop
            - name: POSTGRES_USER
              value: shop
            - name: PGDATA
              value: /var/lib/postgresql/data/pgdata
          envFrom:
            - secretRef:
                name: db-credentials
          readinessProbe:
            exec:
              command: ["pg_isready", "-U", "shop"]
            periodSeconds: 5
          resources:
            requests: { cpu: 250m, memory: 512Mi }
            limits: { memory: 512Mi }
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
      volumes:
        - name: data
          persistentVolumeClaim:
            claimName: db-data
---
apiVersion: v1
kind: Service
metadata:
  name: db
  namespace: shop
spec:
  selector:
    app: db
  ports:
    - port: 5432
      targetPort: 5432

Two decisions deserve explanation. The strategy is Recreate, not the default rolling update, because a ReadWriteOnce volume can be attached to only one node and two Postgres pods must never write to the same files; the old pod stops before the new one starts (rolling updates). And PGDATA points to a subdirectory, because a freshly provisioned volume often contains a lost+found folder that makes the Postgres initialization refuse a non-empty directory.

A Deployment with one replica and a PVC is the simplest way to run a database for a project or a test environment. For production, prefer a StatefulSet or a database operator (running databases and backups), or a managed database outside the cluster.

The web tier: Deployment, Service and Ingress

YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  namespace: shop
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: web
          image: ghcr.io/example/shop-web:1.0.0
          ports:
            - containerPort: 8080
          envFrom:
            - configMapRef:
                name: web-config
          env:
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: db-credentials
                  key: POSTGRES_PASSWORD
          readinessProbe:
            httpGet:
              path: /healthz
              port: 8080
            periodSeconds: 5
          livenessProbe:
            httpGet:
              path: /healthz
              port: 8080
            initialDelaySeconds: 15
          resources:
            requests: { cpu: 200m, memory: 256Mi }
            limits: { memory: 256Mi }
---
apiVersion: v1
kind: Service
metadata:
  name: web
  namespace: shop
spec:
  selector:
    app: web
  ports:
    - port: 80
      targetPort: 8080
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: web
  namespace: shop
spec:
  ingressClassName: nginx
  rules:
    - host: shop.example.test
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web
                port:
                  number: 80

The web Deployment reads the non-secret settings with envFrom and takes only the password from the Secret, renamed to DB_PASSWORD. The readiness probe keeps pods out of the Service until they are ready (probes). The Ingress needs an ingress controller installed in the cluster and a DNS or /etc/hosts entry for the host name (Ingress).

To deploy, save the objects in files (or one file separated by ---) and apply them:

Terminal
kubectl apply -f shop/ --dry-run=server        # validate against the API first
kubectl apply -f shop/
kubectl -n shop rollout status deployment/db
kubectl -n shop rollout status deployment/web
kubectl -n shop get pods,svc,ingress,pvc

A manifest validator

Most failures in a project like this are not YAML syntax errors: they are broken references. A Service selector that matches nothing, an Ingress pointing at a Service that does not exist, a Deployment mounting a claim with a typo. The stand-in below parses a multi-document YAML string and checks the wiring. The manifests are shortened copies of the ones above, with four deliberate problems.

Python Validate the wiring of a two-tier app

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The validator finds the bugs that a plain YAML parser would accept: the db Deployment mounts db-storage while the claim is called db-data, the web Service selects app: webapp while the pods carry app: web, and two other issues, a floating :latest tag and a missing ingressClassName. The real cluster would accept these objects and then fail in puzzling ways at runtime: a pod stuck in Pending for a missing claim, and a Service with no endpoints (troubleshooting). Tools such as kubeconform, kubectl apply --dry-run=server and policy engines (admission and policy) catch many of these before deploy.

How things come up

Knowing the startup order helps you read kubectl get pods during a rollout. The second stand-in plays out the timeline in seconds: the volume binds, the database starts and passes its readiness probe, then the web pods turn Ready and the Service gets endpoints. The numbers are made up, but the order is the real dependency order.

Python Startup timeline of the stack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The web containers start at second 2, before the database is up, but none of them is Ready until the database answers. This is good: the Service never sends users to a pod that cannot reach its data. If your app crashes instead of waiting when the database is missing, you will see a few restarts at the start (pod lifecycle); an init container that waits for the database or retry logic in the app avoids that noise.

Ideas to extend the project

  • Add a HorizontalPodAutoscaler for the web Deployment and a PodDisruptionBudget.
  • Add a NetworkPolicy so that only web pods can reach the database.
  • Move to a StatefulSet for the database and schedule backups (backups).
  • Package everything as a Helm chart with values for dev and prod.
  • Add TLS to the Ingress with a certificate stored in a Secret.

What is real and what is a stand-in

The manifests are valid Kubernetes API objects, but you must supply a real image, a cluster with an ingress controller and a default StorageClass. The validator is a teaching tool that checks a handful of references; the cluster's own validation is stricter in some ways and does not check cross-object wiring at all. The timeline uses invented durations.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the database Deployment use strategy type Recreate?

    During a rolling update the new pod starts before the old one stops. Two database processes on the same files would risk corruption, so the old pod must stop first.
  2. 2. How do the web pods find the database?

    The db Service has a stable name that Kubernetes DNS resolves inside the namespace. The web pods get that name as DB_HOST.
  3. 3. A Service shows no endpoints although all pods are Running and Ready. What should you check first?

    Endpoints are built from the pods that match the Service selector. A typo such as app webapp instead of app web leaves the list empty.
  4. 4. Why is the database password stored in a Secret rather than the ConfigMap?

    Secrets are the object meant for sensitive values and get separate access control and optional encryption at rest. They are base64-encoded, not encrypted, unless you enable encryption.

Summary

  • A typical two-tier app is a ConfigMap, a Secret, a PVC, two Deployments, two Services and an Ingress.
  • Services give stable DNS names: the web tier reaches the database at db; the Ingress reaches the web Service.
  • A single database pod with a ReadWriteOnce volume needs Recreate; production databases deserve a StatefulSet, an operator or a managed service.
  • Most first-deploy failures are broken references between objects, which a validator or --dry-run=server can catch early.
  • Readiness probes decide when pods join a Service, so the startup order is storage, database, web pods, then traffic.

Next: Project: Microservices with Probes and Autoscaling, where you scale this idea to several services.