Kitloft

All tools / Kubernetes examples

Nginx web server on Kubernetes

Nginx serving a static site, with a custom config in a ConfigMap, a Service and an Ingress with TLS from cert-manager.

Customize names, versions →

nginx.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: web-nginx
  namespace: default
data:
  default.conf: |
    server {
        listen 80;
        server_name _;
        root /usr/share/nginx/html;
        location / {
            try_files $uri $uri/ /index.html;
        }
        location = /healthz {
            access_log off;
            return 200 "ok";
        }
    }
  index.html: |
    <!doctype html><title>It works</title><h1>www.example.com is running on Kubernetes</h1>
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  namespace: default
  labels:
    app: web
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: nginx
          image: nginx:1.28
          ports:
            - name: http
              containerPort: 80
          readinessProbe:
            httpGet:
              path: /healthz
              port: http
          livenessProbe:
            httpGet:
              path: /healthz
              port: http
            initialDelaySeconds: 10
          resources:
            requests:
              cpu: 50m
              memory: 32Mi
            limits:
              memory: 128Mi
          volumeMounts:
            - name: conf
              mountPath: /etc/nginx/conf.d/default.conf
              subPath: default.conf
            - name: conf
              mountPath: /usr/share/nginx/html/index.html
              subPath: index.html
      volumes:
        - name: conf
          configMap:
            name: web-nginx
---
apiVersion: v1
kind: Service
metadata:
  name: web
  namespace: default
spec:
  selector:
    app: web
  ports:
    - name: http
      port: 80
      targetPort: http
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: web
  namespace: default
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt
spec:
  ingressClassName: nginx
  tls:
    - hosts: ["www.example.com"]
      secretName: web-tls
  rules:
    - host: www.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web
                port:
                  name: http

How to use it

Commands
kubectl apply -f nginx.yaml
kubectl -n default get pods -w

Prefer Docker Compose? See the Nginx web server Docker Compose version.