使用端口转发来访问集群中的应用

使用端口转发来访问集群中的应用

使用端口转发来访问集群中的应用_第1张图片

个人k8s集群信息:

root@k8s-master:~# kubectl get nodes -o wide
NAME         STATUS   ROLES                  AGE    VERSION   INTERNAL-IP       EXTERNAL-IP   OS-IMAGE             KERNEL-VERSION       CONTAINER-RUNTIME
k8s-master   Ready    control-plane,master   685d   v1.22.0   192.168.123.150           Ubuntu 18.04.5 LTS   4.15.0-213-generic   docker://20.10.0
k8s-node1    Ready                     685d   v1.22.0   192.168.123.151           Ubuntu 18.04.5 LTS   4.15.0-200-generic   docker://20.10.0
k8s-node2    Ready                     685d   v1.22.0   192.168.123.152           Ubuntu 18.04.5 LTS   4.15.0-213-generic   docker://20.10.0

创建一个Nginx Depolyment和服务

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80


root@k8s-master:~# vim nginx-deploy.yml
root@k8s-master:~# kubectl apply -f nginx-deploy.yml
deployment.apps/nginx-deployment created

查看pod:

root@k8s-master:~# kubectl get pod nginx-deployment-585449566-7wt6f -o wide
NAME                               READY   STATUS    RESTARTS   AGE     IP              NODE        NOMINATED NODE   READINESS GATES
nginx-deployment-585449566-7wt6f   1/1     Running   0          2m37s   10.244.36.112   k8s-node1              

创建一个服务:

apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
  selector:
    app: nginx


查看服务信息:

NAME    TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE   SELECTOR
nginx   ClusterIP   10.106.190.56           80/TCP    12s   app=nginx

进入Pod内部修改index.html内容:

root@k8s-master:~# kubectl exec -it nginx-deployment-585449566-7wt6f -- /bin/bash
root@nginx-deployment-585449566-7wt6f:/# echo 'hello kubernetes' > /usr/share/nginx/html/index.html
root@nginx-deployment-585449566-7wt6f:/# exit
exit

然后访问Service:

root@k8s-master:~# kubectl get svc nginx -o wide
NAME    TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE    SELECTOR
nginx   ClusterIP   10.106.190.56           80/TCP    8m3s   app=nginx
root@k8s-master:~# curl 10.106.190.56
hello kubernetes

转发一个本地端口到 Pod 端口

kubectl port-forward 允许使用资源名称 (例如 Pod 名称)来选择匹配的 Pod 来进行端口转发。

root@k8s-master:~# kubectl port-forward service/nginx 22068:80
Forwarding from 127.0.0.1:22068 -> 80
Forwarding from [::1]:22068 -> 80


新启一个shell,本地访问:


root@k8s-master:~# curl 127.0.0.1:22068
hello kubernetes

另一边监听:

Handling connection for 22068

你可能感兴趣的:(云计算,kubernetes,运维,云计算)