如何将节点端口映射到我自己定义的端口



>我有一个可以在8081上访问的服务。如果我通过 docker-compose 或 swarm 进行,而没有对端口进行任何特定更改,那就是工作。

http://$(minikube ip):8081

但是当我通过 Kubernetes(minikube( 运行我的应用程序时,会分配一个 nodePort 在 30000-32767 范围内。 然后我必须调用如下:

http://$(minikube ip):30546

这是我的服务所不能接受的。有没有办法将随机给定的端口映射到我自己定义的端口? 当调用第二个网址时,我收到连接被拒绝 我也用了

kubectl port forward my-service 8081

但仍然没有成功。

kubectl port-forward 命令不正确。 试试下面的一个

kubectl port-forward svc/my-service 8081:8081

然后,您应该能够通过 http//:127.0.0.1:8081 访问该服务

这个答案不是特定于 Minikube,而是适用于在 docker 容器内运行的任何 Kubernetes 集群。

为了将请求从主机发送到容器中运行的 Kubernetes pod,您必须将端口从主机一直映射到 pod。

以下是您的操作方法:

  1. 使用--publish-p将要在容器内使用的 NodePort 发布到主机。
# Map port 8080 on host machine to 31080 inside the container
docker run -p 8080:31080 ...
    创建
  1. 服务时使用自定义节点端口:
# You need to specify the exposed port as the nodePort value
# Otherwise Kubernetes will generate a random nodePort for you 
kubectl create service nodeport myservice --node-port=31080 --tcp=3000:80

Pod 中的应用程序侦听端口80,该端口在端口3000上作为服务公开。在 Kubernetes 节点上的端口 31080 接收的流量将定向到此服务。

发送到主机上的 8080 的查询将遵循以下路径:

Request -> Host Machine -> Docker Container -> Kubernetes Node -> Service -> Pod
↑                   ↑                 ↑              ↑         ↑
localhost:8080         :31080           :31080          :3000      :80

引用:

  • https://docs.docker.com/engine/reference/commandline/run/
  • https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#-em-service-nodeport-em-

最新更新