如何使用 Docker for Windows 在本地主机上访问 kubernetes 服务

How to access kubernetes service on localhost with Docker for Windows

我有 Windows 10 Pro 和 Docker for Windows v18.06.1-ce 启用了 kubernetes。

使用 kubectl create -f,我创建了 rc.yml:

apiVersion: v1
kind: ReplicationController
metadata:
  name: hello-rc
spec:
  replicas: 9
  selector:
    app: hello-world
  template:
    metadata:
      labels:
        app: hello-world
    spec:
      containers:
      - name: hello-ctr
        image: nigelpoulton/pluralsight-docker-ci:latest
        ports:
        - containerPort: 8080

svc.yml

apiVersion: v1
kind: Service
metadata:
  name: hello-svc
  labels:
    app: hello-world
spec:
  type: NodePort
  ports:
  - port: 8080
    nodePort: 30001
    protocol: TCP
  selector:
    app: hello-world

如何访问服务背后的网站?

我希望 localhost:8080 能正常工作,但它没有,10.108.96.27:8080

也没有
> kubectl describe service/hello-svc
Name:                     hello-svc
Namespace:                default
Labels:                   app=hello-world
Annotations:              <none>
Selector:                 app=hello-world
Type:                     NodePort
IP:                       10.108.96.27
LoadBalancer Ingress:     localhost
Port:                     <unset>  8080/TCP
TargetPort:               8080/TCP
NodePort:                 <unset>  30001/TCP
Endpoints:                10.1.0.10:8080,10.1.0.11:8080,10.1.0.12:8080 + 6 more...
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>

有两种方法可以从 Kubernetes 集群向外部世界公开服务:

  1. 类型:LoadBalancer。但是,它仅适用于云提供商。

  2. 类型:节点端口。正如您在这种情况下使用的那样。现在,要访问 Kubernetes 集群内的服务,您需要使用您的一个节点的 IP 地址和字段 nodePort 中的端口 例如,12.34.56.78:30001

有关详细信息,请查看 official documentation

本地开发:

kubectl port-forward <my-pod-name> 8080:8080

您的播客可以在 localhost:8080 上访问。

有关端口转发的更多信息here

这可能会对某些人有所帮助(我每天花 1/2 时间来解决这个问题!)

您可以使用内置的“port-forward”实用程序(正如@aedm 所建议的),但这只会使您的服务可以在本地访问,因为它绑定到环回网络。但您也可以绑定到所有网络并使服务可从外部访问:

kubectl port-forward <service/name> 80:8080 --address='0.0.0.0'

这将使浏览器 (http) 从外部访问它。