Service

本文目录结构

创建Service

创建pod

首先创建pod,层接上节课内容,创建内容如下:

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:
# 部署名字
name: djnode
spec:
replicas: 5
# 用来查找关联的 Pod,所有标签都匹配才行
selector:
matchLabels:
app: djnode
# 定义 Pod 相关数据
template:
metadata:
labels:
app: djnode
spec:
# 定义容器,可以多个
containers:
- name: djnode # 容器名字
image: djangowang77/djnode:v1 # 镜像

创建 Service

通过标签与djnode进行关联,创建service.yaml.

1
2
3
4
5
6
7
8
9
10
11
apiVersion: v1
kind: Service
metadata:
name: djnode
spec:
selector:
app: djnode
type: ClusterIP
ports:
- port: 8080 # 本 Service 的端口
targetPort: 8080 # 容器端口

应用配置“kubectl apply -f service.yaml”,查看servers。

1
2
3
4
kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
djnode NodePort 10.98.196.188 <none> 8080:31000/TCP 64m
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 5h23m

查看服务详情 kubectl describe svc djnode,可以发现 Endpoints 是各个 Pod 的 IP,也就是他会把流量转发到这些节点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
kubectl describe svc djnode
Name: djnode
Namespace: default
Labels: <none>
Annotations: <none>
Selector: app=djnode
Type: ClusterIP
IP Families: <none>
IP: 10.105.106.201
IPs: <none>
Port: <unset> 8080/TCP
TargetPort: 8080/TCP
Endpoints: 172.17.0.2:8080,172.17.0.3:8080,172.17.0.5:8080
Session Affinity: None
Events: <none>

对外暴露服务

修改service.yaml内容如下。

1
2
3
4
5
6
7
8
9
10
11
12
apiVersion: v1
kind: Service
metadata:
name: djnode
spec:
selector:
app: djnode
type: NodePort
ports:
- port: 8080 # 本 Service 的端口
targetPort: 8080 # 容器端口
nodePort: 31000

查看暴露的端口,可以通过web浏览器访问以下端口

1
2
netstat -tnl | grep 31000
tcp 0 0 0.0.0.0:31000 0.0.0.0:* LISTEN