0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

k8sで自分のホスト名を返すnginxのPodとService

Posted at

Pod

nginx-pod.yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
  labels:
    label: nginx-label
spec:
  containers:
  - name: nginx-container
    image: nginx
    ports:
    - containerPort: 80
    command: [ "sh", "-c", "
      ln -sf /etc/hostname /usr/share/nginx/html/index.html;
      nginx -g 'daemon off;';
    "]
$ kubectl apply -f nginx-pod.yaml
pod/nginx-pod created
$ # yaml を使わない場合
$ kubectl run nginx-pod --image=nginx --generator=run-pod/v1 --port=80 --labels=label=nginx-label -- sh -c "ln -sf /etc/hostname /usr/share/nginx/html/index.html; nginx -g 'daemon off;';"
pod/nginx-pod created
$ # 確認 (クラスタ内から nginx-pod を叩く)
$ kubectl run curl --image=curlimages/curl -it --rm --restart=Never -- curl $(kubectl get pod nginx-pod -o jsonpath='{.status.podIP}')
nginx-pod
pod "curl" deleted

Service (NodePort)

nginx-svc.yaml
apiVersion: v1
kind: Service
metadata:
  name: nginx-svc
spec:
  type: NodePort
  ports:
  - port: 8080
    targetPort: 80
    nodePort: 30080 # コメントアウトで空きポートを自動選択
  selector:
    label: nginx-label
$ kubectl apply -f nginx-svc.yaml
service/nginx-svc created
$ # yaml を使わない場合 (nodePort は自動選択)
$ kubectl expose pod nginx-pod --type=NodePort --name=nginx-svc --port=8080 --target-port=80
service/nginx-svc exposed

$ # nodePortを指定
$ kubectl patch svc nginx-svc --type=json -p='[{"op": "replace", "path": "/spec/ports/0/nodePort", "value": 30080}]'
service/nginx-svc patched
$ # 確認 (クラスタ外から叩く)
$ # curl workernode:30080
$ curl $(kubectl get node -o jsonpath='{.items[0].status.addresses[?(@.type=="InternalIP")].address}'):$(kubectl get svc nginx-svc -o jsonpath='{.spec.ports[0].nodePort}')
nginx-pod
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?