port-forward 通过端口转发映射本地端口到指定的应用端口.

在需要调试部署的pod、svc等资源是否提供正常访问时使用。

命令格式:

kubectl port-forward <pod_name> <forward_port> --namespace <namespace> --address <IP默认:127.0.0.1>

实例:

1.我在k8s集群中部署了prometheusnode-exporter服务,用于收集系统的信息.node-exportersvc采用的是ClusterIP模式,端口不能直接对外访问,但是我现在想通过nodeip:port的方式在浏览器测试node-exporter资源是否正常,用port-forward实现,其实这种方法访问方式就类似使用NodePort的访问模式。

[root@localhost ~]# kubectl get svc -n monitoring
NAME                    TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE
grafana                 NodePort    192.168.87.255   <none>        3000:30712/TCP               2d3h
kube-state-metrics      ClusterIP   None             <none>        8443/TCP,9443/TCP            2d3h
node-exporter           ClusterIP   None             <none>        9100/TCP                     2d3h

2、将本地端口9800映射到svc的9100端口,如果不指定address则默认为127.0.0.1的地址.

[root@localhost manifests]# kubectl -n monitoring port-forward svc/node-exporter 9800:9100 --address 10.0.8.101
Forwarding from 10.0.8.101:9800 -> 9100
Handling connection for 9800

3.在浏览器输入nodeip:本地9800端口进行访问.
在这里插入图片描述

4、访问pod

[root@localhost ]# kubectl get pod 
NAME                          READY   STATUS    RESTARTS   AGE
temp-chart-6d4cf56db6-rnbwb   1/1     Running   0          29m
temp-chart-6d4cf56db6-rsxhr   1/1     Running   0          29m
[root@localhost ]# 
[root@localhost ]# kubectl port-forward temp-chart-6d4cf56db6-rsxhr 8090:80 --address 10.0.8.101
Forwarding from 10.0.8.101:8090 -> 80
Handling connection for 8090

通过kubectl port-forwardPod端口到本地

K8S的Service如果是ClusterIP类型,又临时需要以NodePort方式访问,可以通过kubectl port-forward命令将端口映射到本地。

kubectl port-forward svc/kiali 20001:20001 -n istio-system

如上所述,将kiali的20001端口映射到本地的20001端口。通过localhost:20001既可直接访问。

执行后kubectl port-forward后即可访问

k8s(14) : 临时转发容器端口到外部

kubectl port-forward service/hello 8080:8080 --address 0.0.0.0 -n test

前面的8080为宿主机端口,后面的8080pod内部端口

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐