Kubernetes 시작하기
이 문서는 처음에 Ubuntu 26.04 LTS 2026년 4월 릴리스 노트와 비교하여 확인되었습니다. Kubernetes 구성 요소 버전 및 프로덕션 배포 세부 정보는 여전히 MicroK8 및 업스트림 업데이트에 대한 지속적인 검증이 필요합니다.
Kubernetes(약칭 K8s)은 오늘날 가장 인기 있는 컨테이너 오케스트레이션 플랫폼으로, Google에서 오픈소스로 제공하고 CNCF(Cloud Native Computing Foundation)에 기부했습니다. 이는 컨테이너화된 애플리케이션의 배포, 확장 및 관리를 자동화하며 최신 클라우드 네이티브 아키텍처의 초석입니다.
Ubuntu은 Kubernetes을 실행하기 위한 주류 Linux 배포판 중 하나입니다. Canonical는 개발, 테스트 및 엣지 컴퓨팅 시나리오에 이상적인 가볍고 설치가 쉬운 Kubernetes 배포판인 MicroK8s도 제공합니다.
K8이 무엇이고 왜 필요한가요?
K8s 이전의 문제점
컨테이너화 시대에 Docker은 “애플리케이션 패키징 및 실행” 문제를 해결했습니다. 그러나 관리해야 할 컨테이너가 수십 또는 수백 개 있으면 새로운 과제가 발생합니다.
- 컨테이너가 충돌하면 누가 자동으로 다시 시작하나요?
- 트래픽이 증가하면 어떻게 자동 크기 조정을 합니까?
- 컨테이너는 어떻게 서로를 발견하고 통신합니까?
- 서비스 중단 없이 롤링 업데이트를 어떻게 수행합니까?
- 여러 서버에 걸쳐 컨테이너를 어떻게 예약합니까?
K8이 해결하는 것
Kubernetes은 이러한 정확한 문제를 해결하기 위해 구축되었습니다.
| 특징 | 설명 |
|---|---|
| 자가 치유 | 충돌이 발생한 컨테이너를 자동으로 다시 시작합니다. 노드에 장애가 발생하면 워크로드를 마이그레이션합니다. |
| 수평적 확장 | 로드에 따라 컨테이너 인스턴스를 자동으로 늘리거나 줄입니다. |
| 서비스 검색 | 컨테이너는 DNS 이름을 통해 자동 등록되고 서로 액세스합니다. |
| 순차적 업데이트 | 가동 중지 시간 없는 배포를 위해 이전 버전을 점진적으로 교체합니다. |
| 로드 밸런싱 | 여러 컨테이너 인스턴스에 트래픽을 자동으로 분산합니다. |
| 구성 관리 | 애플리케이션 구성 및 비밀의 중앙 집중식 관리 |
MicroK8s 설치
MicroK8s는 Canonical의 경량 Kubernetes이며, 단일 명령으로 Snap를 통해 설치됩니다.
MicroK8 설치
# Install MicroK8s
# Choose the latest stable channel; check snap info microk8s for available versions
sudo snap install microk8s --classic --channel=1.33/stable
# Add current user to the microk8s group (avoid sudo every time)
sudo usermod -a -G microk8s $USER
sudo chown -f -R $USER ~/.kube
# Re-login for group permissions to take effect
newgrp microk8s
# Check installation status
microk8s status --wait-ready공통 추가 기능 활성화
MicroK8s에는 다음과 같은 다양한 추가 기능이 내장되어 있습니다.
# Enable DNS (internal cluster name resolution -- almost always required)
microk8s enable dns
# Enable local storage
microk8s enable hostpath-storage
# Enable Dashboard (web management interface)
microk8s enable dashboard
# Enable Ingress (HTTP reverse proxy)
microk8s enable ingress
# Enable container image registry
microk8s enable registry
# Enable multiple add-ons at once
microk8s enable dns hostpath-storage dashboard ingress
# View all available add-ons
microk8s statuskubectl 별칭 구성
MicroK8s에는 microk8s kubectl이 포함되어 있지만 매번 입력하는 것이 지루합니다. 별칭을 설정할 수 있습니다.
# Option 1: Use an alias
alias kubectl='microk8s kubectl'
echo "alias kubectl='microk8s kubectl'" >> ~/.bashrc
# Option 2: Export config for a standalone kubectl installation
microk8s config > ~/.kube/configkubectl 기본 작업
kubectl은 Kubernetes 클러스터와 상호작용하기 위한 명령줄 도구입니다.
클러스터 정보
# View cluster information
kubectl cluster-info
# View all nodes
kubectl get nodes
# View node details
kubectl describe node <node-name>
# View cluster component status
kubectl get componentstatuses리소스 보기
# View all Pods
kubectl get pods
# View Pods across all namespaces
kubectl get pods --all-namespaces
# Or shorthand
kubectl get pods -A
# View Pod details (wide output)
kubectl get pods -o wide
# View all Deployments
kubectl get deployments
# View all Services
kubectl get services
# Or shorthand
kubectl get svc
# View all resources
kubectl get all리소스 세부정보 및 로그
# View Pod details
kubectl describe pod <pod-name>
# View Pod logs
kubectl logs <pod-name>
# Follow logs in real-time
kubectl logs -f <pod-name>
# View logs for a specific container in a multi-container Pod
kubectl logs <pod-name> -c <container-name>
# Execute commands inside a Pod
kubectl exec -it <pod-name> -- /bin/bash핵심 개념
현물 상환 지불
Pod는 Kubernetes에서 배포 가능한 가장 작은 단위입니다. 포드에는 네트워킹과 스토리지를 공유하는 하나 이상의 컨테이너가 포함되어 있습니다.
# pod-example.yaml
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80# Create a Pod
kubectl apply -f pod-example.yaml
# Check Pod status
kubectl get pod nginx-pod
# Delete a Pod
kubectl delete pod nginx-pod전개
배포는 포드 복제본 수, 롤링 업데이트, 롤백을 관리합니다. 실제로는 포드를 직접 생성하는 경우가 거의 없으며 대신 배포를 통해 관리합니다.
# deployment-example.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.27
ports:
- containerPort: 80
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"# Deploy the application
kubectl apply -f deployment-example.yaml
# View deployment status
kubectl get deployment nginx-deployment
# Scale up/down
kubectl scale deployment nginx-deployment --replicas=5
# View rolling update status
kubectl rollout status deployment nginx-deployment
# Update image version
kubectl set image deployment/nginx-deployment nginx=nginx:1.28
# Rollback to previous version
kubectl rollout undo deployment nginx-deployment
# View update history
kubectl rollout history deployment nginx-deployment서비스
서비스는 포드 세트에 안정적인 네트워크 엔드포인트를 제공합니다. Pod IP는 동적으로 변경되지만 서비스는 고정 액세스 포인트를 제공합니다.
# service-example.yaml
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
type: ClusterIP서비스 유형 설명:
| 유형 | 설명 |
|---|---|
| 클러스터IP | 기본; 클러스터 내에서만 접근 가능 |
| 노드포트 | 모든 노드에서 포트를 엽니다. 외부에서 접근 가능 |
| 로드밸런서 | 클라우드 공급자의 로드 밸런서를 사용합니다. |
# Create a Service
kubectl apply -f service-example.yaml
# View the Service
kubectl get svc nginx-service
# Expose a service with NodePort
kubectl expose deployment nginx-deployment --type=NodePort --port=80첫 번째 애플리케이션 배포
처음부터 끝까지 완전한 웹 애플리케이션을 배포해 보겠습니다.
1단계: 배포 생성
# Quickly create using the command line
kubectl create deployment hello-app --image=gcr.io/google-samples/hello-app:1.0
# Verify the Pod is running
kubectl get pods -l app=hello-app2단계: 서비스 노출
# Create a NodePort Service
kubectl expose deployment hello-app --type=NodePort --port=8080
# View the assigned port
kubectl get svc hello-app3단계: 애플리케이션에 액세스
# Get the access URL
# MicroK8s runs locally by default, so use localhost
NODE_PORT=$(kubectl get svc hello-app -o jsonpath='{.spec.ports[0].nodePort}')
echo "Access URL: http://localhost:$NODE_PORT"
# Test access
curl http://localhost:$NODE_PORT4단계: 규모 확대
# Scale to 3 replicas
kubectl scale deployment hello-app --replicas=3
# View all Pods
kubectl get pods -l app=hello-app5단계: 정리
# Delete the Service and Deployment
kubectl delete svc hello-app
kubectl delete deployment hello-app헬름 패키지 관리
Helm은 Ubuntu의 apt과 유사한 Kubernetes의 패키지 관리자입니다. 차트(패키지)를 사용하여 복잡한 Kubernetes 애플리케이션을 정의, 설치 및 업그레이드합니다.
투구 설치
# Option 1: Install via Snap
sudo snap install helm --classic
# Option 2: Install via official script
curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
# Verify installation
helm version투구 사용
# Add the official stable repository
helm repo add bitnami https://charts.bitnami.com/bitnami
# Update repository index
helm repo update
# Search for Charts
helm search repo nginx
helm search repo mysql
# Install an application (Redis example)
helm install my-redis bitnami/redis
# View installed Releases
helm list
# View Release status
helm status my-redis
# Install with custom configuration
helm install my-nginx bitnami/nginx \
--set replicaCount=3 \
--set service.type=NodePort
# Install with a values file for custom configuration
helm install my-app bitnami/nginx -f custom-values.yaml
# Upgrade a Release
helm upgrade my-redis bitnami/redis --set auth.enabled=false
# Rollback
helm rollback my-redis 1
# Uninstall a Release
helm uninstall my-redis나만의 차트 만들기
# Create a new Chart template
helm create my-chart
# Directory structure
# my-chart/
# Chart.yaml # Chart metadata
# values.yaml # Default configuration values
# templates/ # K8s resource templates
# deployment.yaml
# service.yaml
# ingress.yaml
# Validate the Chart
helm lint my-chart/
# Dry-run install (no actual deployment)
helm install my-release my-chart/ --dry-run --debug
# Package the Chart
helm package my-chart/빠른 참조 명령 테이블
| 작업 | 명령 |
|---|---|
| 클러스터 상태 보기 | kubectl cluster-info |
| 모든 포드 보기 | kubectl get pods -A |
| 포드 로그 보기 | kubectl logs POD_NAME |
| 포드 입력 | kubectl exec -it POD_NAME -- bash |
| 리소스 만들기 | kubectl apply -f file.yaml |
| 리소스 삭제 | kubectl delete -f file.yaml |
| 확장 | kubectl scale deployment NAME --replicas=N |
| 이미지 업데이트 | kubectl set image deployment/NAME container=image |
| 롤백 | kubectl rollout undo deployment/NAME |
| 포트포워딩 | kubectl port-forward pod/NAME 8080:80 |
| 리소스 사용량 보기 | kubectl top pods |
| MicroK8s 상태 | microk8s status |
| MicroK8s 시작 | microk8s start |
| MicroK8s 정지 | microk8s stop |
생산 고려 사항
MicroK8s는 학습 및 개발에 탁월하지만 프로덕션에서 Kubernetes을 사용할 때는 다음 사항을 염두에 두십시오.
- 고가용성 클러스터: 단일 장애 지점을 방지하려면 프로덕션에 최소 3개의 제어 플레인 노드가 필요합니다.
- 리소스 제한: 하나의 애플리케이션이 모든 노드 리소스를 소비하지 않도록 모든 컨테이너에 대해 항상
resources.requests및resources.limits을 설정합니다. - 네트워크 정책: 최소 권한 원칙에 따라 Pod 간 통신을 제한하도록 NetworkPolicy를 구성합니다.
- RBAC 권한: 클러스터 관리자 권한으로 애플리케이션을 실행하지 마세요. 각 서비스에 대한 전용 ServiceAccount 생성
- 이미지 보안: 신뢰할 수 있는 이미지 레지스트리만 사용하고, 이미지의 취약점을 정기적으로 검사하고,
latest태그 사용을 피하세요. - etcd 백업: etcd는 모든 클러스터 상태 데이터를 저장합니다. 정기적인 백업이 중요합니다.
- 모니터링 및 알림: Prometheus + Grafana를 배포하여 클러스터 상태 모니터링
- 로그 수집: 로그 집계를 위해 EFK(Elasticsearch + Fluentd + Kibana) 또는 Loki를 사용합니다.
엔터프라이즈급 지원을 위해서는 Canonical의 Charmed Kubernetes 또는 클라우드 공급자(예: AWS EKS, Google GKE, Azure AKS)의 관리형 K8s 서비스를 고려하세요.
일반적인 문제 해결
# Pod stuck in Pending state
kubectl describe pod <pod-name>
# Usually caused by insufficient resources or node selector mismatch
# Pod in CrashLoopBackOff
kubectl logs <pod-name> --previous
# View logs from the previous crash
# Cannot pull image (ImagePullBackOff)
kubectl describe pod <pod-name>
# Check if the image name is correct and whether image pull credentials are needed
# Service inaccessible
kubectl get endpoints <service-name>
# Verify that the Service selector matches the Pod labels
# DNS resolution failure
kubectl run test --image=busybox --rm -it -- nslookup kubernetes.default
# Check if CoreDNS is running properly위 콘텐츠를 마스터하면 Ubuntu에서 기본 Kubernetes 워크로드를 실행하고 관리할 수 있게 됩니다. 경험이 늘어남에 따라 ConfigMap, Secret, PertantVolume, Ingress, CronJob 및 기타 리소스 유형을 더 자세히 탐색할 수 있습니다.