# Stateless web app: 3 replicas, rolling updates, probes, resources, security context.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  namespace: demo
  labels:
    app.kubernetes.io/name: web
spec:
  replicas: 3
  revisionHistoryLimit: 5
  selector:
    matchLabels:
      app.kubernetes.io/name: web     # must match the template labels below
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1          # at most 1 extra pod during a rollout
      maxUnavailable: 0    # never go below the desired count
  template:
    metadata:
      labels:
        app.kubernetes.io/name: web
    spec:
      securityContext:
        runAsNonRoot: true
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: web
          image: nginxinc/nginx-unprivileged:1.30-alpine   # listens on 8080, runs as non-root
          ports:
            - name: http
              containerPort: 8080
          envFrom:
            - configMapRef:
                name: web-config
          env:
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: web-secrets
                  key: DATABASE_URL
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              memory: 256Mi        # a CPU limit is often left out to avoid throttling
          readinessProbe:          # gate traffic until the app is ready
            httpGet:
              path: /
              port: http
            periodSeconds: 5
          livenessProbe:           # restart the container if it hangs
            httpGet:
              path: /
              port: http
            initialDelaySeconds: 10
            periodSeconds: 10
          startupProbe:            # give slow starters time before liveness kicks in
            httpGet:
              path: /
              port: http
            failureThreshold: 30
            periodSeconds: 2
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          volumeMounts:
            - name: tmp
              mountPath: /tmp
            - name: config
              mountPath: /etc/web
              readOnly: true
      volumes:
        - name: tmp
          emptyDir: {}
        - name: config
          configMap:
            name: web-config
            items:
              - key: app.properties
                path: app.properties
      topologySpreadConstraints:   # spread replicas across nodes
        - maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: ScheduleAnyway
          labelSelector:
            matchLabels:
              app.kubernetes.io/name: web
