创建K8S服务

假设我们已经开发了三个基于Node.js的微服务,需要使用K8S进行部署和管理。这三个微服务分别是kpi,kpitemp和kpicomp,这三个微服务的镜像已经推送到本地镜像库中。现在来看一下构建需求。

首先,这三个微服务都使用配置文件进行配置管理,容器中配置文件保存的目录为/app/config,我们需要可以在主机修改配置文件,这就需要将配置文件所在主机目录映射到容器中的/app/config目录。

第二,kpitemp生成的文件需要在kpi中进行调用,所以,kpitemp的生成文件目录与kpi调用这些文件的目录需要进行映射。这些文件在主机中也可以进行修改,因此,还需要与主机目录进行映射。

第三,kpicomp需要调用kpi中的API,我们希望调用时与部署环境的IP地址无关。

首先创建一个development的部署文件,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
apiVersion: apps/v1
kind: Deployment
metadata:
name: kpi-k8s
spec:
replicas: 1
selector:
matchLabels:
app: kpi-k8s
template:
metadata:
labels:
app: kpi-k8s
spec:
containers:
- name: kpi-k8s
image: "192.168.124.4:5000/kpi:latest"
ports:
- containerPort: 3000
volumeMounts:
- name: kpi-config
mountPath: /app/config
- name: kpi-model
mountPath: /app/modules/kpi
- name: kpi-temp-k8s
image: "192.168.124.4:5000/kpitemp:latest"
ports:
- containerPort: 4000
volumeMounts:
- name: kpi-temp-config
mountPath: /app/config
- name: kpi-model
mountPath: /app/output
- name: kpi-comp-k8s
image: "192.168.124.4:5000/kpicomp:latest"
ports:
- containerPort: 3001
volumeMounts:
- name: kpi-comp-config
mountPath: /app/config
volumes:
- name: kpi-config
hostPath:
path: /run/desktop/mnt/host/c/nodejsdemos/kpidockertest/kpiconfig
- name: kpi-model
hostPath:
path: /run/desktop/mnt/host/c/nodejsdemos/kpidockertest/models
- name: kpi-temp-config
hostPath:
path: /run/desktop/mnt/host/c/nodejsdemos/kpidockertest/kpitempconfig
- name: kpi-comp-config
hostPath:
path: /run/desktop/mnt/host/c/nodejsdemos/kpidockertest/kpicompconfig

首先是文件加载,在每个container的volumeMounts中使用mountPath指定容器中的路径,在volumns中指定hostPath,在hostPath的path属性中指定宿主机的路径,需要注意,如果是windows系统,不能使用C:\这种形式,C盘对应的地址是/run/desktop/mnt/host/c/。

使用这种映射方式,可以映射每个微服务的配置文件路径和工作目录。

接下来配置服务:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
apiVersion: v1
kind: Service
metadata:
name: kpi-k8s-service
spec:
type: NodePort
selector:
app: kpi-k8s
ports:
- port: 3000
name: kpi
targetPort: 3000
nodePort: 30010
- port: 4000
name: kpi-temp
targetPort: 4000
nodePort: 30011
- port: 3001
name: kpi-comp
targetPort: 3001
nodePort: 30012

在服务中定义了需要对外暴露的端口。

如果在微服务之间进行访问,可以使用服务名加端口号:

1
http://kpi-k8s-service:3000/kpi

到这里,第一个微服务创建完成。