我在一个带有标签app=read-write的Pod中有两个容器。容器-1在7110端口上读取,容器-2在7111上侦听。现在我需要通过服务NodePorts连接这些容器。我创建了两个单独的服务来在每个端口(7110和7111)上分配NodePorts。
---
apiVersion: v1
kind: Service
metadata:
labels:
app: read
tier: service
name: read
spec:
ports:
- port: 7110
nodePort: 32000
protocol: TCP
type: NodePort
selector:
app: read
---
apiVersion: v1
kind: Service
metadata:
labels:
app: write
tier: service
name: write
spec:
ports:
- port: 7111
nodePort: 32001
protocol: TCP
type: NodePort
selector:
app: write
但是Services通过匹配标签来连接Pod。所以目前这两个服务不会连接任何pod,因为pod标签是read-write
,服务正在寻找任何标签为read
或write
的pod。在kubernetes中,我们有没有办法在Pod中标记容器?
我唯一的解决方案是为每个Pod创建单个容器并为每个容器分配读写标签。但我真的想将这两个容器保留在单个pod中。
解决方案很简单,我在两个服务中添加了两个标签(具有不同的键),而不是app: read
和app:write
,我在我的服务中添加了read:read-service
和write:write-service
。在Pod中,我在标签和选择器下添加了这两个键;
服务readwrite. yml
---
apiVersion: v1
kind: Service
metadata:
labels:
read: read-service
tier: service
name: read-service
spec:
ports:
- port: 7110
nodePort: 32000
protocol: TCP
type: NodePort
selector:
read: read-service
---
apiVersion: v1
kind: Service
metadata:
labels:
write: write-service
tier: service
name: write-service
spec:
ports:
- port: 7111
nodePort: 32001
protocol: TCP
type: NodePort
selector:
write: write-service
部署. yml
kind: Deployment
apiVersion: extensions/v1beta1
metadata:
creationTimestamp: null
labels:
read: read-service
write: write-service
tier: service
name: if11-read-write
spec:
replicas: 1
selector:
matchLabels:
read: read-service
write: write-service
template:
metadata:
labels:
read: read-service
write: write-service
tier: service
spec:
containers:
- name: read-container-name
...
- name: write-container-name
...
现在由于两个容器都在一个Pod下并且有两个标签,因此read-service将查找带有标签read: read-service
的Pod并分配端口7110和NodePort 32000。