Snippets

K8s snippets

Here are some k8s files I keep re-using when I am building side projects and host them on k8s.

service.yaml

apiVersion: v1
kind: Service
metadata:
  labels:
    app: <SERVICE_NAME>
  name: <SERVICE_NAME>
  namespace: staging
spec:
  ports:
    - name: http
      port: 80
      protocol: TCP
      targetPort: 8080
  selector:
    app: <SERVICE_NAME>
  type: ClusterIP

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: <SERVICE_NAME>
  namespace: staging
  labels:
    app: <SERVICE_NAME>
spec:
  replicas: 2
  selector:
    matchLabels:
      app: <SERVICE_NAME>
  strategy:
    rollingUpdate:
      maxUnavailable: 0
      maxSurge: 1
  template:
    metadata:
      labels:
        app: <SERVICE_NAME>
    spec:
      containers:
        - name: web
          image: <CONTAINER REGISTRY/IMAGE>
          imagePullPolicy: Always
          ports:
            - name: http
              containerPort: 8080
      imagePullSecrets:
        - name: github-token
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30

ingress.yaml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    cert-manager.io/issuer: letsencrypt-prod
  name: <SERVICE_NAME>-ingress-http
  namespace: staging
spec:
  ingressClassName: nginx
  rules:
    - host: <HOST.COM>
      http:
        paths:
          - backend:
              service:
                name: <SERVICE_NAME>
                port:
                  number: 80
            path: /
            pathType: Prefix
  tls:
    - hosts:
        - <HOST.COM>
      secretName: <SECRET_NAME>-tls-prod

kustomization.yaml

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

namespace: staging

resources:
- deployment.yaml
- service.yaml
- ingress.yaml
images:
- name: <CONTAINER REGISTRY IMAGE:TAG>
  newTag: <TAG>

To edit the image with kustomize, usually I put it in a deployment script or in a deployment CI stage.

kustomize edit set image <CONTAINER REGISTRY IMAGE:TAG>

applying the changes to the cluster:

kustomize build k8s/ | k apply -f -