Kubernetes Deployment + Service 简介

引言

K8S集群搭建

在K8s集群搭建完成后,这篇文章简单介绍一下DeploymentService的关系。

编写yaml

其中 kind 有很多种,可以看见我写了2个kind,只不过放在了一个yml中。一个是service一个是deployment.

apiVersion: extensions/v1beta1 # 如果使用apps/v1beata1 那么readiness探针将会报错
kind: Deployment
metadata:
  name: test-nginx
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: web_server
    spec:
      containers:
      - name: nginx
        image: nginx
        readinessProbe: # 探针,只为了判断容器启动后是否存在这个文件,如果不存在那么ready永远都会是0/1
          httpGet:
            port: 80
            path: /index.html
          initialDelaySeconds: 3
          periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  type: NodePort # Type 有很多种 如果是ClusterIP那么nodePort将无效
  ports:
  - protocol: TCP
    port: 8081 # 集群对内的通信端口
    targetPort: 80 # 容器内默认的nginx端口
    nodePort: 30080 # 集群对外的通信端口
    name: test
  selector:
    app: web_server

Deployment

这个kind是为了部署服务而使用的,创建deployment一定会创建出pod,因为k8s中pod是基础单位,记得吗?

deployment

Service

在很久前那篇用手机写的K8S和docker简介里,我们说过Service可以理解为docker swarmoverlay的新的解决方案。
为什么说k8s更偏向服务,就是因为里面的Service.
容器启动后默认监听的端口是80,还记得docker中我们怎么开启对外监听的吗?-p 参数或使用overlay网络。把容器内的80端口映射到宿主机其他端口。

我们看看刚才通过yml部署后,service中有什么。
service
其中CLUSTER-IP,其实在apiserver配置文件中就有。
cluster-ip

Cluster-IP是用来集群内通信的地址和端口。
我们在service中可以看见10.254.145.143,也就是说在集群内访问这个10.254.145.143:8081,就可以访问到nginx服务。

而外网则需要访问外网IP:30080才可以访问到nginx服务

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐