(共566篇)
全部分类

访问集群中的应用程序
[ Docker ] 

通过创建 service 访问

如果应用程序是通过 deployment 创建的, 可以通过下面的方式创建一个 Service 资源:

1
2
3
4
--type=NodePort         # Service类型, 值有ClusterIP(默认值), NodePort, LoadBalancer, ExternalName四种
--name=service-name     # Service名称
--port=8080             # Service本身的端口
--target-port=80        # 应用程序的端口
1
kubectl expose deploy deploy-name --type=NodePort --name=service-name --port=8080 --target-port=80

此时通过kubectl describe svc service-name查看一下创建的 service 资源信息, 类似于这样:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
Name: patch-service
Namespace: default
Labels: <none>
Annotations: <none>
Selector: app=nginx
Type: NodePort
IP Family Policy: SingleStack
IP Families: IPv4
IP: 10.99.18.140
IPs: 10.99.18.140
Port: <unset>  8080/TCP
TargetPort: 80/TCP
NodePort: <unset>  31160/TCP # 这是自动给servie分配的外部访问端口
Endpoints: 10.244.1.36:80
Session Affinity: None
External Traffic Policy: Cluster
Events: <none>

现在, 在集群内的主机可以通过localhost:31160访问应用程序, 或者在集群外的主机上通过http://集群内任意节点IP:31160访问应用程序

在集群外主机通过端口转发访问

相当于在集群外主机开通一个 proxy, 需要在集群之外的主机上执行 port-forward 命令

如果应用程序是通过 deployment 创建的, 像下面这样, 80 表示应用程序使用的端口, 57749 表示本地要访问的端口, 如果不设置此端口, kubectl 会自动分配, 下面方式启动后在集群外的主机上, 通过localhost:57749访问到应用程序

1
2
3
4
$ kubectl port-forward deploy deploy-name 57749:80
# orwarding from 127.0.0.1:57749 -> 80
# Forwarding from [::1]:57749 -> 80
# Handling connection for 57749

也可以直接转发打指定的 Pod 上, 以下面方式启动后, 可以在集群外主机上通过localhost:57782访问到应用程序, 通常不建议这么做, 因为这种方法完全失去了 K8S 的意义,如果 pod 崩溃, 应用程序就访问不到了

1
2
3
4
$ kubectl port-forward pod/patch-demo-66586975bd-8jg8z :80
# Forwarding from 127.0.0.1:57782 -> 80
# Forwarding from [::1]:57782 -> 80
# Handling connection for 57782