Kubernetes はじめに
この記事は、最初に Ubuntu 26.04 LTS 2026 年 4 月リリース ノートと照合してチェックされました。 Kubernetes コンポーネントのバージョンと運用展開の詳細については、MicroK8 およびアップストリームの更新に対する継続的な検証がまだ必要です。
Kubernetes (K8s と略称) は、現在最も人気のあるコンテナ オーケストレーション プラットフォームであり、Google によってオープンソース化され、CNCF (Cloud Native Computing Foundation) に寄付されています。コンテナ化されたアプリケーションの展開、スケーリング、管理を自動化し、最新のクラウドネイティブ アーキテクチャの基礎となります。
Ubuntu は、Kubernetes を実行するための主流の Linux ディストリビューションの 1 つです。 Canonical は、開発、テスト、エッジ コンピューティングのシナリオに最適な、軽量でインストールが簡単な Kubernetes ディストリビューションである MicroK8s も提供します。
K8s とは何か、そしてなぜそれが必要なのか
K8 以前の問題点
コンテナ化時代、Dockerは「アプリケーションをパッケージ化して実行する」という問題を解決しました。しかし、管理すべきコンテナが数十、さらには数百になると、次のような新たな課題が生じます。
- コンテナがクラッシュした場合、誰が自動的に再起動するのでしょうか?
- トラフィックが増加した場合、どのように自動スケールしますか?
- コンテナはどのようにして相互に検出し、通信するのでしょうか?
- サービスを中断せずにローリング アップデートを実行するにはどうすればよいですか?
- 複数のサーバー間でコンテナーをスケジュールするにはどうすればよいですか?
K8s が解決するもの
Kubernetes は、まさに次の問題に対処するために構築されました。
| 特徴 | 説明 |
|---|---|
| 自己修復 | クラッシュしたコンテナを自動的に再起動します。ノードに障害が発生した場合にワークロードを移行します |
| 水平スケーリング | 負荷に基づいてコンテナインスタンスを自動的に増減します |
| サービスの検出 | コンテナは自動登録され、DNS 名を介して相互にアクセスします |
| ローリングアップデート | ダウンタイムゼロの展開のために古いバージョンを段階的に置き換えます |
| 負荷分散 | 複数のコンテナインスタンスにトラフィックを自動的に分散します。 |
| 構成管理 | アプリケーション構成とシークレットの一元管理 |
MicroK8sのインストール
MicroK8s は、Canonical の軽量 Kubernetes であり、Snap 経由で 1 つのコマンドでインストールされます。
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中心となる概念
ポッド
ポッドは、Kubernetes でデプロイ可能な最小単位です。ポッドには、ネットワークとストレージを共有する 1 つ以上のコンテナが含まれています。
# 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サービス
Service は、一連の 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最初のアプリケーションのデプロイ
完全な Web アプリケーションを最初から最後までデプロイしてみましょう。
ステップ 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-appステップ 2: サービスを公開する
# Create a NodePort Service
kubectl expose deployment hello-app --type=NodePort --port=8080
# View the assigned port
kubectl get svc hello-appステップ 3: アプリケーションにアクセスする
# 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_PORTステップ 4: スケールアップ
# Scale to 3 replicas
kubectl scale deployment hello-app --replicas=3
# View all Pods
kubectl get pods -l app=hello-appステップ 5: クリーンアップ
# Delete the Service and Deployment
kubectl delete svc hello-app
kubectl delete deployment hello-appHelm パッケージ管理
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 つのコントロール プレーン ノードが必要です
- リソース制限: 1 つのアプリケーションがすべてのノード リソースを消費しないように、コンテナーごとに
resources.requestsおよびresources.limitsを常に設定します。 - ネットワーク ポリシー: 最小特権の原則に従ってポッド間の通信を制限するように NetworkPolicy を構成します。
- RBAC 権限: クラスター管理者権限でアプリケーションを実行しないでください。サービスごとに専用の ServiceAccount を作成する
- イメージ セキュリティ: 信頼できるイメージ レジストリのみを使用し、定期的にイメージの脆弱性をスキャンし、
latestタグの使用を避けます。 - etcd をバックアップします: etcd はすべてのクラスター状態データを保存します — 定期的なバックアップが重要です
- 監視とアラート: Prometheus + Grafana をデプロイしてクラスターの健全性を監視します
- ログ収集: ログの集約には EFK (Elasticsearch + Fluentd + Kibana) または Loki を使用します。
エンタープライズ グレードのサポートについては、Canonical の 魅力的な 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上記の内容を習得すると、基本的な Kubernetes ワークロードを Ubuntu 上で実行および管理できるようになります。経験が増えるにつれて、ConfigMap、Secret、Persistent Volume、Ingress、CronJob、およびその他のリソース タイプをさらに詳しく調べることができます。