当我们创建pod时,仅仅是创建了pod,要为其创建rc(ReplicationController),他才会有固定的副本,然后为其创建service,集群内部才能访问该pod,使用 NodePort 或者 LoadBalancer 类型的 Service,外部网络也可以访问该pod;每个 service 会创建出来一个虚拟 ip,通过访问 vip:port 就能获取服务的内容(内部访问,因为这是一个vip,外部无法访问的)
创建service时,其配置文件中的selector:指定后端绑定的pod,例如serviceA的selector:
app:whoimi
env:dev
然后有一个podA,
labels:
app:whoimi
env:dev
然后有一个podB,
labels:
app:whoimi
env:dev
那么我们的serviceA 就会绑定podA,podB,绑定的pod的ip会填写到serviceA的endpoint中,内部访问(vip:port方式访问)serviceA,根据serviceA的vip:port直接访问,serviceA会随机的将服务转发给后端的pod(podA,podB)
# cat nginx01.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment01
spec:
selector:
matchLabels:
env: prod
replicas: 1
template:
metadata:
labels:
env: prod
spec:
containers:
- name: nginx
image: nginx:1.11
ports:
- containerPort: 80
# cat nginx02.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment02
spec:
selector:
matchLabels:
env: prod
replicas: 1
template:
metadata:
labels:
env: prod
spec:
containers:
- name: nginx
image: nginx:1.11
ports:
- containerPort: 80
# cat service-test.yaml
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
env: prod
ports:
- name: http
protocol: TCP
port: 80
targetPort: 80
nodePort: 30011
type: NodePort