Kubernetes入門と実践 - 基本概念から実際のアプリケーションデプロイまでの完全ガイド

Tech Trends AI
- 5 minutes read - 948 wordsKubernetesは、コンテナオーケストレーションのデファクトスタンダードとして、モダンなアプリケーション開発において欠かせない技術となっています。本記事では、Kubernetesの基本概念から実際のアプリケーションデプロイまでを包括的に解説します。
Kubernetesとは
Kubernetesは、Googleが開発したオープンソースのコンテナオーケストレーションプラットフォームです。複数のコンテナを効率的に管理し、スケーリング、ロードバランシング、自動復旧などの機能を提供します。
なぜKubernetesが必要なのか
従来の問題
- コンテナの手動管理の複雑さ
- サービス発見とロードバランシングの困難
- 障害時の自動復旧が困難
- スケーリングの複雑性
Kubernetesのメリット
- 宣言的な設定管理
- 自動スケーリングとセルフヒーリング
- サービス発見とロードバランシング
- ローリングアップデートとロールバック
- リソースの効率的な利用
Kubernetesの基本概念
1. Pod
Podは、Kubernetesにおける最小のデプロイ単位です。
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
spec:
containers:
- name: nginx
image: nginx:1.21
ports:
- containerPort: 80
Podの特徴
- 1つ以上のコンテナを含む
- 同一Pod内のコンテナは同じネットワークとストレージを共有
- 一緒にスケジュールされ、一緒に削除される
2. Deployment
Deploymentは、Podのレプリカセットを管理し、宣言的なアップデートを提供します。
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.21
ports:
- containerPort: 80
Deploymentの機能
- レプリカの管理
- ローリングアップデート
- ロールバック機能
- スケーリング
3. Service
Serviceは、Podへの安定したネットワークアクセスを提供します。
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
type: LoadBalancer
Serviceの種類
- ClusterIP: クラスター内部からのみアクセス可能
- NodePort: 各ノードの特定ポートでアクセス可能
- LoadBalancer: クラウドプロバイダーのロードバランサーを使用
- ExternalName: 外部サービスへのエイリアス
4. ConfigMapとSecret
ConfigMap: 設定データの管理
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
database_url: "mysql://localhost:3306/mydb"
debug: "true"
Secret: 機密データの管理
apiVersion: v1
kind: Secret
metadata:
name: app-secret
type: Opaque
data:
username: YWRtaW4= # base64エンコード済み
password: cGFzc3dvcmQ=
実践: Webアプリケーションのデプロイ
ステップ1: 環境構築
minikubeを使用してローカル環境を構築:
# minikubeのインストール(macOS)
brew install minikube
# minikubeの開始
minikube start
# kubectlの設定確認
kubectl cluster-info
Docker Desktopを使用する場合:
# Docker DesktopでKubernetesを有効化
# Settings > Kubernetes > Enable Kubernetes
# 設定確認
kubectl config current-context
ステップ2: サンプルアプリケーションの作成
app.yaml - フロントエンドアプリケーション
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend-app
labels:
app: frontend
spec:
replicas: 2
selector:
matchLabels:
app: frontend
template:
metadata:
labels:
app: frontend
spec:
containers:
- name: frontend
image: nginx:1.21
ports:
- containerPort: 80
volumeMounts:
- name: config
mountPath: /etc/nginx/conf.d
volumes:
- name: config
configMap:
name: nginx-config
---
apiVersion: v1
kind: Service
metadata:
name: frontend-service
spec:
selector:
app: frontend
ports:
- protocol: TCP
port: 80
targetPort: 80
type: LoadBalancer
---
apiVersion: v1
kind: ConfigMap
metadata:
name: nginx-config
data:
default.conf: |
server {
listen 80;
location / {
proxy_pass http://backend-service:8080;
}
}
backend.yaml - バックエンドAPI
apiVersion: apps/v1
kind: Deployment
metadata:
name: backend-app
labels:
app: backend
spec:
replicas: 3
selector:
matchLabels:
app: backend
template:
metadata:
labels:
app: backend
spec:
containers:
- name: backend
image: node:16-alpine
command: ["node"]
args: ["-e", "const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify({message: 'Hello from Kubernetes!', timestamp: new Date().toISOString()})); }); server.listen(8080, () => { console.log('Server running on port 8080'); });"]
ports:
- containerPort: 8080
env:
- name: NODE_ENV
value: "production"
- name: DB_HOST
valueFrom:
secretKeyRef:
name: db-secret
key: host
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"
---
apiVersion: v1
kind: Service
metadata:
name: backend-service
spec:
selector:
app: backend
ports:
- protocol: TCP
port: 8080
targetPort: 8080
type: ClusterIP
---
apiVersion: v1
kind: Secret
metadata:
name: db-secret
type: Opaque
data:
host: bG9jYWxob3N0 # localhost のbase64エンコード
username: YWRtaW4= # admin のbase64エンコード
password: cGFzc3dvcmQ= # password のbase64エンコード
ステップ3: アプリケーションのデプロイ
# アプリケーションの適用
kubectl apply -f backend.yaml
kubectl apply -f app.yaml
# デプロイメントの状況確認
kubectl get deployments
kubectl get pods
kubectl get services
# アプリケーションの動作確認
kubectl port-forward service/frontend-service 8080:80
# ブラウザでhttp://localhost:8080にアクセス
ステップ4: スケーリングと更新
# レプリカ数の変更
kubectl scale deployment backend-app --replicas=5
# ローリングアップデート
kubectl set image deployment/backend-app backend=node:18-alpine
# ロールアウト状況の確認
kubectl rollout status deployment/backend-app
# ロールバック
kubectl rollout undo deployment/backend-app
高可用性とモニタリング
ヘルスチェックの実装
apiVersion: apps/v1
kind: Deployment
metadata:
name: app-with-healthcheck
spec:
replicas: 3
selector:
matchLabels:
app: webapp
template:
metadata:
labels:
app: webapp
spec:
containers:
- name: webapp
image: nginx:1.21
ports:
- containerPort: 80
livenessProbe:
httpGet:
path: /health
port: 80
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 80
initialDelaySeconds: 5
periodSeconds: 5
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"
Horizontal Pod Autoscaler (HPA)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: webapp-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: webapp
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
トラブルシューティング
よくある問題と対処法
1. Podが起動しない
# Pod の詳細確認
kubectl describe pod <pod-name>
# ログの確認
kubectl logs <pod-name>
# イベントの確認
kubectl get events --sort-by=.metadata.creationTimestamp
2. Serviceに接続できない
# Serviceの確認
kubectl get svc
kubectl describe svc <service-name>
# Endpointsの確認
kubectl get endpoints <service-name>
# ネットワークのテスト
kubectl run debug --image=busybox -it --rm -- sh
# 上記コマンド内で: nslookup <service-name>
3. リソース不足
# ノードのリソース使用状況
kubectl top nodes
# Podのリソース使用状況
kubectl top pods
# リソース制限の確認
kubectl describe node <node-name>
セキュリティベストプラクティス
1. Network Policies
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-backend
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 8080
2. RBAC (Role-Based Access Control)
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: pod-reader
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "watch", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-pods
namespace: default
subjects:
- kind: User
name: developer
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
3. Pod Security Standards
apiVersion: v1
kind: Pod
metadata:
name: secure-pod
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
fsGroup: 2000
containers:
- name: app
image: nginx:1.21
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
volumeMounts:
- name: tmp
mountPath: /tmp
- name: cache
mountPath: /var/cache/nginx
volumes:
- name: tmp
emptyDir: {}
- name: cache
emptyDir: {}
運用のベストプラクティス
1. リソース管理
# リソースクォータの設定
apiVersion: v1
kind: ResourceQuota
metadata:
name: compute-quota
spec:
hard:
requests.cpu: "4"
requests.memory: 8Gi
limits.cpu: "8"
limits.memory: 16Gi
persistentvolumeclaims: "10"
2. デプロイメント戦略
Blue-Greenデプロイメント
# Blue環境
apiVersion: apps/v1
kind: Deployment
metadata:
name: app-blue
labels:
version: blue
spec:
replicas: 3
selector:
matchLabels:
app: myapp
version: blue
template:
metadata:
labels:
app: myapp
version: blue
spec:
containers:
- name: app
image: myapp:1.0.0
---
# Green環境
apiVersion: apps/v1
kind: Deployment
metadata:
name: app-green
labels:
version: green
spec:
replicas: 3
selector:
matchLabels:
app: myapp
version: green
template:
metadata:
labels:
app: myapp
version: green
spec:
containers:
- name: app
image: myapp:2.0.0
3. モニタリングとログ
# Prometheusを使用したモニタリング
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install prometheus prometheus-community/kube-prometheus-stack
# ログ集約のためのFluentd
kubectl apply -f https://raw.githubusercontent.com/fluent/fluentd-kubernetes-daemonset/master/fluentd-daemonset-elasticsearch-rbac.yaml
まとめ
本記事では、Kubernetesの基本概念から実際のアプリケーションデプロイまでを包括的に解説しました。
学習のポイント
- 基本概念の理解: Pod、Service、Deploymentの役割と関係性
- 実践的な経験: 実際のアプリケーションのデプロイとスケーリング
- 運用の考慮: セキュリティ、モニタリング、トラブルシューティング
次のステップ
- Helmを使用したパッケージ管理
- CI/CDパイプラインとの統合
- マルチクラスター管理
- サービスメッシュの導入
Kubernetesは学習コストが高い技術ですが、マスターすることで現代的なアプリケーション運用の基盤を構築できます。実際に手を動かしながら、少しずつ理解を深めていくことが重要です。
Kubernetes環境の構築やトラブルシューティングでお困りの際は、公式ドキュメントやコミュニティのリソースを積極的に活用しましょう。