Mac 访问本地运行的kubernetes的pod容器

573 阅读1分钟

前言

由于使用本地docker desktop 安装的kubernetes,所以启动pods后,无法在本地通过ip访问。

解决方案

将pods暴露位一个服务
kubectl expose pods podName -n namespaceName --type=NodePort --name diyName
kubectl get service -n namespaceName

» kubectl get po
NAME    READY   STATUS    RESTARTS   AGE
web-0   1/1     Running   0          155m
web-1   1/1     Running   0          155m

» kubectl expose pods web-0 --type=NodePort --name my-web-0
service/my-web-0 exposed

» kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP          28h
my-web-0     NodePort    10.105.106.72    <none>        80:32445/TCP     15s
nginx        ClusterIP   None             <none>        80/TCP           156m
nginx-svc    ClusterIP   10.100.224.240   <none>        80/TCP,443/TCP   136m

» curl 127.0.0.1:32445
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

查看该svc的yaml

apiVersion: v1
kind: Service
metadata:
  creationTimestamp: "2022-07-03T13:46:20Z"
  labels:
    app: nginx
    controller-revision-hash: web-6949d64dc8
    statefulset.kubernetes.io/pod-name: web-0
  name: my-web-0
  namespace: default
  resourceVersion: "84037"
  uid: 6e775774-550e-4561-9cb8-27e6e0f4cb42
spec:
  clusterIP: 10.105.106.72
  clusterIPs:
  - 10.105.106.72
  externalTrafficPolicy: Cluster
  internalTrafficPolicy: Cluster
  ipFamilies:
  - IPv4
  ipFamilyPolicy: SingleStack
  ports:
  - nodePort: 32445
    port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: nginx
    controller-revision-hash: web-6949d64dc8
    statefulset.kubernetes.io/pod-name: web-0
  sessionAffinity: None
  type: NodePort
status:
  loadBalancer:
    ingress:
    - hostname: localhost

其实就是将pod暴露成一个type为nodePort的service,这样就可以通过外部访问了