Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Project: Deploy a Secure Three-Tier App on OpenShift

Put the chapter together: create a project with quota, deploy database, API and web tiers with secrets, storage, routes, network policies, autoscaling and a final readiness check.

This project ties together everything from networking to administration. You will plan and deploy a small shop: a web frontend, an API and a PostgreSQL database, in one project, with a TLS route, secrets, persistent storage, network policies, quotas and autoscaling. Work through the plan on paper or on a practice cluster (OpenShift Local or a developer sandbox).

OpenShift cannot run on this site, so the manifests and oc commands are for your own cluster, and the runnable code is a Python checker that validates your plan the way a review would. Image names are placeholders; replace them with your own images.

Architecture

flowchart LR
  U["Users"] -->|"HTTPS"| R["Route (edge TLS)"]
  R --> W["web (2 pods)"]
  W --> A["api (2-6 pods, HPA)"]
  A --> D[("postgres (1 pod + PVC)")]

Only the route reaches the web tier; only web reaches the API; only the API reaches the database.

Step 1: project, quota and defaults

Terminal
oc new-project shop --display-name="Shop" --description="Three-tier demo"
oc create quota shop-quota --hard=requests.cpu=4,requests.memory=8Gi,limits.cpu=8,limits.memory=16Gi,pods=20,persistentvolumeclaims=3
oc apply -f limitrange.yaml          # defaults: 100m/128Mi requests, 500m/512Mi limits
oc adm policy add-role-to-group view qa-team -n shop

See quotas and limit ranges and RBAC.

Step 2: secrets and the database

Terminal
oc create secret generic db-credentials \
  --from-literal=POSTGRES_USER=shop \
  --from-literal=POSTGRES_PASSWORD="$(openssl rand -base64 18)" \
  --from-literal=POSTGRES_DB=shop
YAML
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: db
spec:
  serviceName: db
  replicas: 1
  selector:
    matchLabels: { app: db }
  template:
    metadata:
      labels: { app: db, tier: data }
    spec:
      containers:
        - name: postgres
          image: registry.example.com/shop/postgres:16
          envFrom:
            - secretRef: { name: db-credentials }
          ports:
            - { name: pg, containerPort: 5432 }
          volumeMounts:
            - { name: data, mountPath: /var/lib/postgresql/data }
          readinessProbe:
            exec: { command: ["pg_isready", "-U", "shop"] }
          resources:
            requests: { cpu: 250m, memory: 512Mi }
            limits: { cpu: "1", memory: 1Gi }
  volumeClaimTemplates:
    - metadata: { name: data }
      spec:
        accessModes: ["ReadWriteOnce"]
        resources: { requests: { storage: 10Gi } }
---
apiVersion: v1
kind: Service
metadata:
  name: db
spec:
  clusterIP: None
  selector: { app: db }
  ports:
    - { name: pg, port: 5432 }

The database image must run as an arbitrary UID (SCCs); a Red Hat or other OpenShift-ready PostgreSQL image does. The claim template gives the pod its own volume (persistent volumes).

Step 3: the API tier with autoscaling

Terminal
oc create deployment api --image=registry.example.com/shop/api:1.0 --replicas=2
oc set env deployment/api --from=secret/db-credentials --prefix=DB_
oc set env deployment/api DB_HOST=db DB_PORT=5432
oc set resources deployment/api --requests=cpu=200m,memory=256Mi --limits=cpu=1,memory=512Mi
oc set probe deployment/api --readiness --get-url=http://:8080/healthz
oc expose deployment/api --port=8080
oc autoscale deployment/api --min=2 --max=6 --cpu-percent=70

Label the pods with a tier label so policies can select them: oc label deployment/api tier=backend (also add it to the pod template for the policy to see it; with the YAML form, set spec.template.metadata.labels). See autoscaling.

Step 4: web tier and route

Terminal
oc create deployment web --image=registry.example.com/shop/web:1.0 --replicas=2
oc set env deployment/web API_URL=http://api:8080
oc expose deployment/web --port=8080
oc create route edge shop --service=web --hostname=shop.apps.mycluster.example.com
oc patch route shop -p '{"spec":{"tls":{"insecureEdgeTerminationPolicy":"Redirect"}}}'

Details: routes and TLS termination.

Step 5: network policies

YAML
# 1. Deny all ingress in the project
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: deny-all }
spec:
  podSelector: {}
  policyTypes: ["Ingress"]
---
# 2. Router -> web
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: web-from-router }
spec:
  podSelector: { matchLabels: { app: web } }
  ingress:
    - from:
        - namespaceSelector:
            matchLabels: { network.openshift.io/policy-group: ingress }
---
# 3. web -> api
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: api-from-web }
spec:
  podSelector: { matchLabels: { app: api } }
  ingress:
    - from:
        - podSelector: { matchLabels: { app: web } }
      ports: [{ port: 8080 }]
---
# 4. api -> db
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: db-from-api }
spec:
  podSelector: { matchLabels: { app: db } }
  ingress:
    - from:
        - podSelector: { matchLabels: { app: api } }
      ports: [{ port: 5432 }]

Remember the monitoring allowance if you scrape metrics (network policies).

Step 6: verification script

The checker below models your finished project as data and reports gaps. Edit the dictionary to match what you built and re-run it.

Python Stand-in: project readiness checker

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.

Now break something on purpose: set "readiness": False for the API, change the route policy, delete a network policy name, and run again. The messages are the same kind of findings an admin would make in a review.

Use these commands against the real project to confirm each claim:

Terminal
oc get all,pvc,networkpolicy,quota,hpa
oc get route shop
oc get pods -o custom-columns=NAME:.metadata.name,SCC:.metadata.annotations.openshift\\.io/scc
oc exec deploy/web -- curl -s -m 3 http://api:8080/healthz      # expected to work
oc exec deploy/web -- curl -s -m 3 db:5432                      # expected to time out
curl -I http://shop.apps.mycluster.example.com                  # expected 302 redirect

Extensions

  1. Move the database credentials to an external vault operator.
  2. Add a ServiceMonitor and an alert for API error rate (monitoring).
  3. Add a PodDisruptionBudget for web and API, then think about how a cluster update affects them (updates).
  4. Add a canary release: a second API version with oc set route-backends through a route in front of it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the database service headless in this design?

    A headless service gives the StatefulSet pods stable per-pod DNS records.
  2. 2. Which object lets only the web tier reach the API on port 8080?

    After deny-all, an allow policy on the API pods with a podSelector for web opens just that path.
  3. 3. Why set insecureEdgeTerminationPolicy: Redirect on the route?

    Redirect answers HTTP with a redirect to the HTTPS URL.
  4. 4. What must the API pods declare so the HPA can compute CPU utilization?

    Utilization is measured against the CPU request.

Summary

  • A project needs quota, defaults, access control and a plan before workloads.
  • Secrets feed the database and API; a StatefulSet and PVC keep data.
  • Services connect tiers; a TLS route exposes only the web tier.
  • Deny-all plus targeted policies enforce who talks to whom.
  • Requests, probes, HPA and a readiness review make the app production-minded.

Next: Practice: oc command drills