1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【簡単Kubernetes】【kubectl】Kubernetes における nginx Deployment と Service の構築手順まとめ

Posted at

本記事では、Kubernetes クラスタ上で nginx の Deployment と Service を構築し、外部からアクセスするまでの一連の手順を解説します。実際に利用する yaml ファイルのサンプルと、各フィールドの意味も丁寧に解説します。


1. nginx Deployment の作成

まず、nginx Pod を管理する Deployment を作成します。

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment  # Deployment の名称
  labels:                 # リソースの識別に使われるラベル
    app: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80

ポイント解説:

  • labels により、後述の Service がこの Pod を選択できます。
  • replicas で起動する Pod の数を指定しています。

2. Service の作成(NodePort タイプ)

次に、Pod に外部からアクセスするための Service を作成します。ここでは NodePort タイプを使用します。

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
  labels:
    app: nginx
spec:
  selector:
    app: nginx  # Deployment で定義したラベルと一致させる
  ports:
  - name: nginx-port
    protocol: TCP
    port: 80
    targetPort: 80
    nodePort: 32600
  type: NodePort

フィールドの意味:

  • port: Cluster 内で Service が公開するポート。
  • targetPort: Pod がリッスンしているポート。
  • nodePort: 外部からアクセスするためのポート(30000-32767 の範囲)。

- はリスト形式でポートを複数定義できることを示します。


3. 適用と確認

kubectl apply -f nginx-deployment.yaml
kubectl apply -f nginx-service.yaml
kubectl get pods -o wide
kubectl get services -o wide

nginx-service が表示され、EXTERNAL-IPPORT(S) の情報が確認できれば成功です。


4. 動作確認

以下のコマンドで、実際に nginx にアクセスできるか確認します。

curl http://<任意ノードのIP>:32600

クラウド利用時の注意

クラウド環境(AWS, GCP 等)では、セキュリティグループなどで 32600 ポートのアクセス許可が必要です。


5. 補足:kubectl get の便利なオプション

  • 全ての namespace のリソースを表示:
kubectl get deployments --all-namespaces
kubectl get pods --all-namespaces
  • 特定 namespace のリソースを表示:
kubectl get deployments -n kube-system
kubectl get pods -n kube-system
  • 略記の利用例:
kubectl get po pod1  # "pods" は "po" と省略可

おわりに

本記事では、nginx Deployment と NodePort タイプの Service の作成から、外部アクセスの確認方法までを丁寧に解説しました。

Kubernetes における Service やラベルセレクタの概念をしっかり理解することで、柔軟でスケーラブルなアプリケーション運用が可能になります。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?