手当たり次第に書くんだ

飽きっぽいのは本能

Kubernetes Nginx コンテナと Service LoadBalancer

Nginx Deployment に LoadBalancer Service を作成し、MetalLB などで割り当てた VIP からアクセスできるようにします。

考え方

LoadBalancer は、Pod に直接アクセスするのではなく、label selector で対象 Pod を束ねるための Service です。Deployment の Pod が作り直されても、Service 名を入口として扱えます。

Namespace と Deployment

kubectl create namespace nginx-loadbalancer-ns

kubectl -n nginx-loadbalancer-ns apply -f - <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deploy
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: nginx:latest
          ports:
            - containerPort: 80
EOF

LoadBalancer Service

kubectl -n nginx-loadbalancer-ns apply -f - <<'EOF'
apiVersion: v1
kind: Service
metadata:
  name: nginx-svc
spec:
  type: LoadBalancer
  selector:
    app: nginx
  ports:
    - name: http
      port: 80
      targetPort: 80
EOF

確認

kubectl -n nginx-loadbalancer-ns get deploy,pod,svc -o wide
kubectl -n nginx-loadbalancer-ns describe svc nginx-svc

VIP への接続確認

kubectl -n nginx-loadbalancer-ns get svc nginx-svc
VIP=$(kubectl -n nginx-loadbalancer-ns get svc nginx-svc -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
curl -I http://${VIP}/

まとめ

Nginx を題材にすると、Pod、Deployment、Service の役割を段階的に確認できます。Pod 単体で動作を見て、ClusterIP、NodePort、LoadBalancer の順に入口を広げると理解しやすくなります。

Kubernetes Nginx コンテナと Service LoadBalancer

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)

トップへ戻る