☁️ Cloud

Kubernetes

K8s / Kubernetes

The container orchestration standard. Developed by Google. Automated deployment, scaling, and recovery.

📖 Detailed Explanation

Kubernetes (K8s) is an open-source platform that automates the deployment, scaling, and management of containerized applications. It was developed based on Borg, the system Google used internally, and is now managed by the CNCF (Cloud Native Computing Foundation). The name means 'helmsman' in Greek.

As core concepts, a Pod is the smallest deployment unit and contains one or more containers. A Deployment manages declarative updates of Pods and supports rolling updates and rollbacks. A Service provides network access to a set of Pods, and an Ingress defines HTTP/HTTPS routing from outside to services within the cluster.

The architecture consists of the Control Plane and Worker Nodes. The Control Plane includes the API Server (the entry point for all requests), etcd (stores cluster state), the Scheduler (decides Pod placement), and the Controller Manager (monitors and reconciles state). On the Worker Node, the kubelet (manages the Pod lifecycle), kube-proxy (manages network rules), and the Container Runtime (Docker, containerd, etc.) run.

Major cloud managed services include AWS EKS, GCP GKE, and Azure AKS. Managed services automatically manage the Control Plane, reducing operational burden, and make integration with cloud services (IAM, load balancers, storage) easy.

💻 Code Example

# 클러스터 정보 확인
kubectl cluster-info
kubectl get nodes -o wide

# 네임스페이스 생성 및 기본 설정
kubectl create namespace production
kubectl config set-context --current --namespace=production

# Pod 생성 및 관리
kubectl run nginx --image=nginx:1.25 --port=80
kubectl get pods -o wide
kubectl describe pod nginx
kubectl logs nginx -f
kubectl exec -it nginx -- /bin/bash

# Deployment 생성 (명령형)
kubectl create deployment web --image=nginx:1.25 --replicas=3

# 스케일링
kubectl scale deployment web --replicas=5

# 롤링 업데이트
kubectl set image deployment/web nginx=nginx:1.26
kubectl rollout status deployment/web
kubectl rollout history deployment/web

# 롤백
kubectl rollout undo deployment/web
kubectl rollout undo deployment/web --to-revision=2

# 서비스 노출
kubectl expose deployment web --port=80 --type=LoadBalancer

# 리소스 모니터링
kubectl top nodes
kubectl top pods
kubectl get events --sort-by='.lastTimestamp'

# 디버깅
kubectl describe pod 
kubectl logs  --previous   # 이전 컨테이너 로그
kubectl debug  -it --image=busybox

# 리소스 삭제
kubectl delete deployment web
kubectl delete pod nginx --grace-period=0 --force
# deployment.yaml - 프로덕션 웹 애플리케이션
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-app
  namespace: production
  labels:
    app: web-app
    version: v1.0.0
spec:
  replicas: 3
  revisionHistoryLimit: 5          # 롤백용 히스토리 보관
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1                   # 업데이트 중 추가 Pod
      maxUnavailable: 0             # 항상 최소 replicas 유지
  selector:
    matchLabels:
      app: web-app
  template:
    metadata:
      labels:
        app: web-app
        version: v1.0.0
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "8080"
    spec:
      terminationGracePeriodSeconds: 30
      serviceAccountName: web-app-sa

      # 토폴로지 분산 (가용영역 분산)
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: topology.kubernetes.io/zone
          whenUnsatisfiable: ScheduleAnyway
          labelSelector:
            matchLabels:
              app: web-app

      containers:
        - name: web
          image: myregistry/web-app:v1.0.0
          imagePullPolicy: IfNotPresent
          ports:
            - name: http
              containerPort: 8080
              protocol: TCP

          # 환경 변수
          env:
            - name: NODE_ENV
              value: "production"
            - name: DB_HOST
              valueFrom:
                secretKeyRef:
                  name: db-credentials
                  key: host
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name

          # 리소스 제한
          resources:
            requests:
              cpu: "250m"
              memory: "256Mi"
            limits:
              cpu: "1000m"
              memory: "512Mi"

          # Liveness Probe - 컨테이너 재시작 결정
          livenessProbe:
            httpGet:
              path: /health
              port: 8080
            initialDelaySeconds: 15
            periodSeconds: 20
            timeoutSeconds: 5
            failureThreshold: 3

          # Readiness Probe - 트래픽 수신 결정
          readinessProbe:
            httpGet:
              path: /ready
              port: 8080
            initialDelaySeconds: 5
            periodSeconds: 10
            timeoutSeconds: 3
            successThreshold: 1
            failureThreshold: 3

          # Startup Probe - 시작 시간이 긴 앱용
          startupProbe:
            httpGet:
              path: /health
              port: 8080
            failureThreshold: 30
            periodSeconds: 10

          # 볼륨 마운트
          volumeMounts:
            - name: config
              mountPath: /app/config
              readOnly: true
            - name: tmp
              mountPath: /tmp

      volumes:
        - name: config
          configMap:
            name: web-app-config
        - name: tmp
          emptyDir: {}

      # 이미지 Pull Secret
      imagePullSecrets:
        - name: regcred

---
# HorizontalPodAutoscaler
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: web-app-hpa
  namespace: production
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: web-app
  minReplicas: 3
  maxReplicas: 50
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70
    - type: Resource
      resource:
        name: memory
        target:
          type: Utilization
          averageUtilization: 80
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
        - type: Percent
          value: 10
          periodSeconds: 60
    scaleUp:
      stabilizationWindowSeconds: 0
      policies:
        - type: Pods
          value: 4
          periodSeconds: 15
# ClusterIP Service (내부 통신용)
apiVersion: v1
kind: Service
metadata:
  name: web-app
  namespace: production
spec:
  type: ClusterIP
  selector:
    app: web-app
  ports:
    - name: http
      port: 80
      targetPort: 8080
      protocol: TCP

---
# LoadBalancer Service (외부 노출)
apiVersion: v1
kind: Service
metadata:
  name: web-app-lb
  namespace: production
  annotations:
    # AWS NLB 설정
    service.beta.kubernetes.io/aws-load-balancer-type: "nlb"
    service.beta.kubernetes.io/aws-load-balancer-scheme: "internet-facing"
spec:
  type: LoadBalancer
  selector:
    app: web-app
  ports:
    - name: http
      port: 80
      targetPort: 8080
    - name: https
      port: 443
      targetPort: 8080

---
# Ingress (HTTP 라우팅)
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: web-app-ingress
  namespace: production
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/proxy-body-size: "50m"
    cert-manager.io/cluster-issuer: "letsencrypt-prod"
spec:
  tls:
    - hosts:
        - api.example.com
        - www.example.com
      secretName: example-tls
  rules:
    - host: api.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web-app
                port:
                  number: 80
    - host: www.example.com
      http:
        paths:
          - path: /api
            pathType: Prefix
            backend:
              service:
                name: api-backend
                port:
                  number: 80
          - path: /
            pathType: Prefix
            backend:
              service:
                name: frontend
                port:
                  number: 80

---
# NetworkPolicy (네트워크 보안)
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: web-app-policy
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: web-app
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              name: ingress-nginx
        - podSelector:
            matchLabels:
              app: frontend
      ports:
        - protocol: TCP
          port: 8080
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: database
      ports:
        - protocol: TCP
          port: 5432
    - to:
        - namespaceSelector: {}
          podSelector:
            matchLabels:
              k8s-app: kube-dns
      ports:
        - protocol: UDP
          port: 53

💬 How It's Used in Practice

Architecture Design Meeting

PM: "We're planning to run a new project on Kubernetes, and we're torn between building the cluster ourselves and using a managed service."

DevOps: "For a production environment, I'd recommend a managed service. With AWS EKS or GKE, Control Plane high availability, etcd backups, and version upgrades are handled automatically. Building it yourself lowers the initial cost, but the burden of operations staff and incident response is large. For our team's size, I think it's best to start with a managed service and review a multi-cluster strategy once traffic exceeds 100,000 DAU."

Interview Questions

Interviewer: "How do you implement zero-downtime deployments in Kubernetes?"

Candidate: "I use the RollingUpdate strategy of a Deployment. If you set maxSurge to 1 and maxUnavailable to 0, the existing replica count is always maintained. The key is the readinessProbe configuration: a new Pod is added to the Service only when it is actually ready to handle traffic. I also add a sleep to the preStop hook to give existing connections time to drain, and set terminationGracePeriodSeconds sufficiently. If Blue-Green is needed, I sometimes use Argo Rollouts."

Incident Response

Developer: "My Pod keeps restarting in a CrashLoopBackOff state. What could the problem be?"

SRE: "First, check the Events with kubectl describe pod. If it's OOMKilled, the memory limit is insufficient, and if the livenessProbe is failing, you need to check the app's status. Look at the previous container's logs with kubectl logs --previous, and if it's an app that takes a long time to start, add a startupProbe or increase initialDelaySeconds. If it started after a recent deployment, it's faster to roll back with kubectl rollout undo and then analyze the cause."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

❌

Resource Requests/Limits Not Set

If you don't set resources.requests and limits, nodes may be over-consumed or scheduling may fail. In particular, running without a memory limit can let an OOM affect other Pods as well. Set namespace-level defaults with LimitRange and ResourceQuota.

❌

Using the latest Tag Image

If you use :latest as the image tag, you cannot track which version was deployed. Rollbacks are also difficult, and when used together with imagePullPolicy: Always, Pods of different versions can run in the same Deployment. Always use a fixed version tag (v1.2.3 or a git commit SHA).

✅

Guaranteeing Availability with Pod Disruption Budget

Setting a PDB (PodDisruptionBudget) during node upgrades or scale-downs guarantees the minimum number of available Pods. Set minAvailable or maxUnavailable so that the service is not interrupted even during cluster maintenance.

🔗 Related Terms

📚 Learn More