• 本页内容

expose 暴露服务


Kubernetes 中的服务(Service)是一种抽象概念,它定义了 Pod 的逻辑集和访问 Pod 的协议。Service 使从属 Pod 之间的松耦合成为可能。

expose

对外暴露一个服务,可以使用 expose 命令外完成,支持如下资源:

  • pod (po)
  • service (svc)
  • replicationcontroller (rc)
  • deployment (deploy)
  • replicaset (rs)

有一个如下的 deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: webapp
spec:
  replicas: 1
  selector:
    matchLabels:
      app: webapp
  template:
    metadata:
      labels:
        app: webapp
    spec:
      containers:
      - image: nginx
        imagePullPolicy: IfNotPresent
        name: webapp
        ports:
        - name: http
          containerPort: 80
          protocol: TCP

暴露上述 deployment 服务的命如下:

$ kubectl expose deployment webapp --type=NodePort --port=80 --target-port=http --name=webapp-svc
service/webapp-svc exposed

注意:如果 deploymentspec.template.spec.containers.ports.name 没有指定,则只能使用 --target-port=80

查看 webapp—svc 的 Selector 与 Deployment 是一致的,,均为 app=webapp

$ kubectl get svc webapp-svc -o wide
NAME         TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE   SELECTOR
webapp-svc   NodePort   10.96.114.205   <none>        80:31628/TCP   74s   app=webapp

$ kubectl get deployment webapp -o wide
NAME     READY   UP-TO-DATE   AVAILABLE   AGE    CONTAINERS   IMAGES   SELECTOR
webapp   1/1     1            1           117s   webapp       nginx    app=webapp

关于 expose 的命令的更多用法,使用如下命令查阅:

kubectl help expose