123DevOps··9 min read

Deploy and scale an nginx application on Kubernetes, step by step

A walkthrough tested end to end: namespace, an nginx Deployment with requests, limits, and probes, a ConfigMap with index.html, a Service, port-forward, kubectl scale, an HPA (and what happens without metrics-server), rollout, and rollback.

Kubernetes

A first deployment on Kubernetes is often a quick kubectl run nginx and that’s it. A real deployment needs more: declared resources, health checks, configuration kept outside the image, a stable Service, scaling, and a safe way back when the new version misbehaves. This guide builds all of that with nginx, and every command was run on a kind cluster with Kubernetes 1.37 (1 control plane and 2 workers). The outputs are real, just shortened.

What we’ll build

Object Role
Namespace b-nginx Isolates the resources and makes cleanup easy
ConfigMap nginx-html Keeps index.html outside the image
Deployment nginx Keeps N Pod replicas running and handles rollouts
Service nginx Stable IP and DNS name in front of the Pods
HorizontalPodAutoscaler nginx Adjusts replicas based on CPU

Save each manifest in a numbered file (00-namespace.yaml, 10-configmap.yaml…) in a single folder; that way one kubectl apply -f . applies everything in order.

Namespace and a ConfigMap with index.html

The namespace is created with the Pod Security Admission label at the baseline level, which blocks privileged configurations:

apiVersion: v1
kind: Namespace
metadata:
  name: b-nginx
  labels:
    pod-security.kubernetes.io/enforce: baseline
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-html
  namespace: b-nginx
data:
  index.html: |
    <!doctype html>
    <html lang="en">
      <head><meta charset="utf-8"><title>Hello from Kubernetes</title></head>
      <body><h1>Hello from Kubernetes!</h1><p>Served by nginx in a Deployment.</p></body>
    </html>

The ConfigMap will be mounted as a volume, so changing the content doesn’t require rebuilding the image.

The Deployment: resources and probes

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  namespace: b-nginx
  labels:
    app.kubernetes.io/name: nginx
spec:
  replicas: 2
  revisionHistoryLimit: 5
  selector:
    matchLabels:
      app.kubernetes.io/name: nginx
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  template:
    metadata:
      labels:
        app.kubernetes.io/name: nginx
    spec:
      containers:
        - name: nginx
          image: nginx:1.29-alpine
          ports:
            - name: http
              containerPort: 80
          resources:
            requests:
              cpu: 50m
              memory: 32Mi
            limits:
              memory: 64Mi
          readinessProbe:
            httpGet:
              path: /
              port: http
            periodSeconds: 5
          livenessProbe:
            httpGet:
              path: /
              port: http
            initialDelaySeconds: 5
            periodSeconds: 10
          volumeMounts:
            - name: html
              mountPath: /usr/share/nginx/html
              readOnly: true
      volumes:
        - name: html
          configMap:
            name: nginx-html

Requests and limits

requests is what the scheduler reserves on the node; it’s also the baseline for the HPA, which measures CPU as a percentage of the request. Without a CPU request, utilization-based HPA doesn’t work. The memory limit keeps a leaking Pod from taking down the node. We left CPU without a limit on purpose, to avoid throttling; the topic is covered in scheduling and resources.

Readiness and liveness

The readinessProbe decides whether the Pod is part of the Service: while it fails, the Pod gets no traffic. The livenessProbe restarts the container if it hangs. With maxSurge: 1 and maxUnavailable: 0, the rollout only removes an old Pod after the new one is ready, which guarantees no loss of capacity during the switch.

For static nginx, both probes can point at /. In real applications, split the endpoints: readiness can check dependencies (database, cache), but liveness should only check that the process is alive. If liveness depends on the database, a database outage restarts every Pod at once and turns a partial problem into a full outage.

Service and a port-forward test

apiVersion: v1
kind: Service
metadata:
  name: nginx
  namespace: b-nginx
spec:
  selector:
    app.kubernetes.io/name: nginx
  ports:
    - name: http
      port: 80
      targetPort: http

Applying everything:

$ kubectl apply -f .
namespace/b-nginx created
configmap/nginx-html created
deployment.apps/nginx created
service/nginx created

$ kubectl -n b-nginx rollout status deploy/nginx --timeout=120s
deployment "nginx" successfully rolled out

$ kubectl -n b-nginx get pods,svc -o wide
NAME                         READY   STATUS    IP            NODE
pod/nginx-76cccd8988-hkx8g   1/1     Running   10.244.1.17   blog-lab-worker2
pod/nginx-76cccd8988-trfzj   1/1     Running   10.244.2.16   blog-lab-worker

NAME            TYPE        CLUSTER-IP     PORT(S)   SELECTOR
service/nginx   ClusterIP   10.96.67.149   80/TCP    app.kubernetes.io/name=nginx

The Service is a ClusterIP, which means it only exists inside the cluster. To test from your machine, use port-forward:

$ kubectl -n b-nginx port-forward svc/nginx 8082:80 &
Forwarding from 127.0.0.1:8082 -> 80

$ curl -si http://127.0.0.1:8082/
HTTP/1.1 200 OK
Server: nginx/1.29.8
Content-Type: text/html

<!doctype html>
<html lang="en">
  <head><meta charset="utf-8"><title>Hello from Kubernetes</title></head>
  <body><h1>Hello from Kubernetes!</h1><p>Served by nginx in a Deployment.</p></body>
</html>

port-forward is a debugging tool, not a way to expose the application. That’s what Service types and the Gateway API are for, covered in the introduction to Services.

Scaling with kubectl scale

$ kubectl -n b-nginx scale deploy/nginx --replicas=5
deployment.apps/nginx scaled

$ kubectl -n b-nginx get endpointslices -l kubernetes.io/service-name=nginx
NAME          ADDRESSTYPE   PORTS   ENDPOINTS                                         AGE
nginx-d5mfj   IPv4          80      10.244.2.16,10.244.1.17,10.244.2.17 + 2 more...   10s

New Pods join the Service on their own as soon as they pass readiness. From inside the cluster, the full DNS name answers too:

$ kubectl -n b-nginx run curl --rm -i --restart=Never --image=curlimages/curl -- \
    -s http://nginx.b-nginx.svc.cluster.local/ | grep h1
  <body><h1>Hello from Kubernetes!</h1><p>Served by nginx in a Deployment.</p></body>

Keep in mind that kubectl scale is imperative: the next kubectl apply with replicas: 2 in the manifest undoes the change. If scaling is going to be automatic, remove replicas from the manifest (the reason is explained in the Kubernetes API and objects).

HPA: automatic scaling (and why it needs metrics-server)

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: nginx
  namespace: b-nginx
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: nginx
  minReplicas: 2
  maxReplicas: 10
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 300

The HPA reads Pod CPU through the Resource Metrics API (metrics.k8s.io), whose definition became stable in Kubernetes 1.37. But the API needs something to serve it, usually metrics-server, and the lab cluster doesn’t have one. Here’s what happens:

$ kubectl -n b-nginx get hpa nginx
NAME    REFERENCE          TARGETS              MINPODS   MAXPODS   REPLICAS   AGE
nginx   Deployment/nginx   cpu: <unknown>/70%   2         10        5          45s

$ kubectl -n b-nginx describe hpa nginx
...
Conditions:
  Type           Status  Reason                   Message
  ----           ------  ------                   -------
  AbleToScale    True    SucceededGetScale        the HPA controller was able to get the target's current scale
  ScalingActive  False   FailedGetResourceMetric  the HPA was unable to compute the replica count: failed to get cpu utilization: unable to get metrics for resource cpu: unable to fetch metrics from resource metrics API: the server could not find the requested resource (get pods.metrics.k8s.io)

$ kubectl top pods -n b-nginx
error: Metrics API not available

Three things to notice. The target shows as <unknown>. The ScalingActive=False condition explains why. And the HPA doesn’t touch the replicas: the 5 from kubectl scale stayed in place, even with maxReplicas and minReplicas set. The describe output also shows the default scale-up behavior (up to 4 Pods or 100% every 15 seconds) and the 300-second scale-down window, which is the HPA default and was made explicit in the manifest.

To enable it, install metrics-server (at the time of writing, the latest version is v0.9.1; check the current docs):

kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml

This step was not run on the shared lab cluster. On local clusters like kind, you often need to adjust the kubelet TLS verification in the metrics-server arguments; check the project README. To scale on queues, events, or business metrics, look at KEDA.

Rolling out a new version and rolling back

Changing any field in the template creates a new revision. For this part, I recreated the Deployment from the manifest (back to 2 replicas) and switched the image to nginx:1.28-alpine. It’s an older version, chosen only for the demo; in real life it would be your next release. The kubernetes.io/change-cause annotation becomes the revision’s description in the history:

$ kubectl -n b-nginx annotate deploy/nginx kubernetes.io/change-cause="initial version 1.29-alpine"
$ kubectl -n b-nginx set image deploy/nginx nginx=nginx:1.28-alpine
$ kubectl -n b-nginx annotate deploy/nginx kubernetes.io/change-cause="downgrade to 1.28-alpine" --overwrite

$ kubectl -n b-nginx rollout status deploy/nginx --timeout=120s
Waiting for deployment "nginx" rollout to finish: 1 out of 2 new replicas have been updated...
Waiting for deployment "nginx" rollout to finish: 1 old replicas are pending termination...
deployment "nginx" successfully rolled out

$ kubectl -n b-nginx rollout history deploy/nginx
REVISION  CHANGE-CAUSE
1         initial version 1.29-alpine
2         downgrade to 1.28-alpine

Watch the order. In a first test, I annotated before set image, and revisions 1 and 2 ended up with the same description: the Deployment’s annotation is copied to the current ReplicaSet and then to the new one. Annotate right after the change or, better, put the annotation in the manifest itself, in the same commit as the new image.

Something went wrong? Go back to the previous revision:

$ kubectl -n b-nginx rollout undo deploy/nginx
Warning: resource deployments/nginx was previously managed with 'kubectl apply'. Rolling back will not update the kubectl.kubernetes.io/last-applied-configuration annotation, which may cause unexpected behavior on future 'kubectl apply' operations. Consider using 'kubectl apply' with your previous configuration file instead.
deployment.apps/nginx rolled back

$ kubectl -n b-nginx rollout history deploy/nginx
REVISION  CHANGE-CAUSE
2         downgrade to 1.28-alpine
3         initial version 1.29-alpine

$ kubectl -n b-nginx get rs -o wide
NAME               DESIRED   CURRENT   READY   IMAGES
nginx-6bcdfcbd69   0         0         0       nginx:1.28-alpine
nginx-76cccd8988   2         2         2       nginx:1.29-alpine

Notice three details. The rollback created revision 3 by reusing the old ReplicaSet, which was kept around with 0 replicas (that’s what revisionHistoryLimit is for). To go to a specific revision, use --to-revision=N. And the kubectl warning matters: undo changes the live object, but not your manifest. In teams that use GitOps, the right rollback is to revert the commit and let Argo CD apply it. For canary, blue/green, and other strategies, see scaling and updating applications.

Cleanup

Since everything lives in one namespace, cleanup is a single command, and the garbage collector removes the Deployment, ReplicaSets, Pods, Service, HPA, and ConfigMap:

$ kubectl delete -f .
namespace "b-nginx" deleted
configmap "nginx-html" deleted from b-nginx namespace
deployment.apps "nginx" deleted from b-nginx namespace
service "nginx" deleted from b-nginx namespace
horizontalpodautoscaler.autoscaling "nginx" deleted from b-nginx namespace

Checklist

  • Declare CPU and memory requests and a memory limit on every container
  • Configure readiness and liveness probes that hit lightweight endpoints
  • Use maxUnavailable: 0 for rollouts without capacity loss
  • Keep configuration out of the image with ConfigMaps
  • Make sure metrics-server is installed before creating CPU-based HPAs
  • Record the reason for every rollout and test rollout undo before you need it
  • Prefer rolling back through Git when deployments are done with GitOps

A deployment is only done when you know how to scale it, observe it, and roll it back without improvising.

Get updates on new posts and stay in the loop!