LoginSignup
0
0

NginxコンテナをIngressで公開する

Posted at

初めに

IngressはKubernetesクラスター内のServiceに対する外部からのアクセスを管理するオブジェクトです.URIベースで複数のサービスに割り振ることができるので便利です.

実装の概要図

実装の概要図は以下に示します.
image.png

Kubernetes Clusterはrke2で実装します.
この記事に従うと組み立てられます.

クラスタに配置するものは以下です.

  • Ingress
  • Nginx Service (Cluster IP)
  • Nginx Pod

実装

rke2で組み立てたKubernetesクラスタ内に実装するもののYAMLファイルをそれぞれ示します.

Step1
testという名前のNameSpaceを作成

$ kubectl create namespace test

Step2
NginXの構築を行います.

作業ディレクトリの作成

$ mkdir nginx

デプロイメントの作成

$ vi nginx/nginx-deployment.yaml

Nginxのデプロイメントが以下です.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    component: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      component: nginx
  template:
    metadata:
      labels:
        component: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.20

移動

$ cd nginx

testのNameSpaceに作成

$ kubectl apply -f nginx-deployment.yaml -n test

次はServiceの作成です.Cluster IPで公開するNginxのServiceは以下です.

$ vi nginx/nginx-service.yaml

ファイルサービスの名前はmy-first-serviceとします.

apiVersion: v1
kind: Service
metadata:
  name: my-first-service
spec:
  selector:
    component: nginx
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
  type: ClusterIP

移動

$ cd nginx

Serviceの作成

$ kubectl apply -f nginx-service.yaml -n test

Step3
作業ディレクトリの作成

$ mkdir ingress

移動

$ cd ingress

ファイルの作成

$ vi ingress.yaml

metadate/namespaceはNginxを作成したtestに作成します.
service/nameは先ほど作成したmy-first-serviceというservice名にします.
Ingressの設定は以下になります.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: test-ingress
  namespace: test
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  ingressClassName: nginx
  rules:
  - http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: my-first-service
            port:
              number: 80

Nginxを作成したNameSpaceにIngressを作成します.

$ kubectl apply -f ingress.yaml -n test

Ingressができているか確認します.
ADDRESSに192.168.150.1と192.168.150.2と192.168.150.3のIPアドレスが振られているためできています.

$ kubectl get ingress -n test
NAME               CLASS   HOSTS   ADDRESS                                         PORTS   AGE
test-ingress   nginx   *       192.168.150.1,192.168.150.2,192.168.150.3   80      8h

Step4
アクセスができるかどうかを確認します.
ブラウザでhttp://IPアドレス:80 と入力しましょう!以下の画面が出ればOKです!

参考

0
0
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
0
0