4

kubernetes中的服务类型

 3 years ago
source link: https://www.yangyanxing.com/article/type-in-k8s.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

kubernetes中的服务类型

当我们使用deployment或者RS创建了一些pod时,比如创建了一个nginx的pod,该pod中有三个replicas,此时,如果我们查看pod状态大概是这个样子的

nginx-deploy.yaml 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: nginx-app
name: nginxapp
spec:
selector:
matchLabels:
app: nginx-app
replicas: 3
template:
metadata:
labels:
app: nginx-app
spec:
containers:
- image: nginx
name: nginxapp
ports:
- containerPort: 80

我们创建并查看pod情况

1
2
3
4
5
6
7
8
#kubectl apply -f nginx-deploy.yaml
deployment.apps/nginxapp created

#kubectl get pod
NAME READY STATUS RESTARTS AGE
nginxapp-59946895d9-gt4xw 1/1 Running 0 20s
nginxapp-59946895d9-ld2dt 1/1 Running 0 49s
nginxapp-59946895d9-v2cd7 1/1 Running 0 20s

使用 -o wide 参数查看看加详细的内容

1
2
3
4
5
kubectl get pod -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
nginxapp-59946895d9-gt4xw 1/1 Running 0 2m18s 10.1.0.58 docker-desktop <none> <none>
nginxapp-59946895d9-ld2dt 1/1 Running 0 2m47s 10.1.0.56 docker-desktop <none> <none>
nginxapp-59946895d9-v2cd7 1/1 Running 0 2m18s 10.1.0.57 docker-desktop <none> <none>

可以看到它们分别被创建在了 10.1.0.56,10.1.0.57,10.1.0.58上,但是使用浏览器访问这三个地址,并不会得到响应,如果想要访问到创建的nginx pod,还需要再创建与之对应的service.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
apiVersion: v1
kind: Service
metadata:
labels:
app: nginxlabelser
name: nginxlabelser
spec:
ports:
- protocol: TCP
port: 80
targetPort: 80
selector:
app: nginx-app
type: NodePort

它使用的type是NodePort,

1
2
3
4
kubectl get service
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 3d8h
nginxlabelser NodePort 10.105.36.53 <none> 80:31844/TCP 90s

Service 目前有 4 种类型:

  • ClusterIP: 是 K8S 当前默认的 Service 类型。将 service 暴露于一个仅集群内可访问的虚拟 IP 上。
  • NodePort: 是通过在集群内所有 Node 上都绑定固定端口的方式将服务暴露出来,这样便可以通过 : 访问服务了。
  • LoadBalancer: 是通过 Cloud Provider 创建一个外部的负载均衡器,将服务暴露出来,并且会自动创建外部负载均衡器路由请求所需的 NodeportClusterIP
  • ExternalName: 是通过将服务由 DNS CNAME 的方式转发到指定的域名上将服务暴露出来,这需要 kube-dns 1.7 或更高版本支持。

如果使用了NodePort的话,则可以通过node:port 的方式访问到,此时我们通过http://127.0.0.1:31844 则可以正常的访问。

本文由 杨彦星 发表于 杨彦星的个人博客 ,采用「署名 4.0 国际」创作共享协议。
非商业转载请注明作者及出处。商业转载请联系作者本人。
本文标题为: kubernetes中的服务类型

本文链接为:https://www.yangyanxing.com/article/type-in-k8s.html

欢迎关注我的公众号--序语程言,里面会分享一些编程的基础与一些问题的解决

qrcode.jpg

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK