【问题标题】:How to expose an "election-based master and secondaries" service outside Kubernetes cluster?如何在 Kubernetes 集群外公开“基于选举的主从”服务?
【发布时间】:2018-03-29 20:31:24
【问题描述】:

我一直在尝试在 Kubernetes 中实现一个服务,其中每个 Pod 都需要从集群外部访问。

我的服务的拓扑很简单:3 个成员,其中一个随时充当 master(基于选举);写入主要;读去中学。顺便说一下,这是MongoDB副本集。

它们在内部 Kubernetes 集群中没有问题,但在外部 我唯一拥有的是NodePort 服务类型,它将传入连接负载平衡到其中一个它们,但我需要分别访问它们中的每一个,具体取决于我想从客户端执行的操作(写入或读取)。

我应该使用哪种 Kubernetes 资源来为我的服务中的每个成员提供单独的访问权限?

【问题讨论】:

    标签: mongodb kubernetes


    【解决方案1】:

    为了从外部访问每个 pod,您可以为每个 pod 创建单独的服务并使用NodePort 类型。

    因为 Service 使用选择器来访问可用的后端,所以您可以只为 master 创建一个 Service:

    apiVersion: v1
    kind: Service
    metadata:
      name: my-master
      labels:
        run: my-master
    spec:
      type: NodePort
      ports:
      - port: #your-external-port
        targetPort: #your-port-exposed-in-pod
        protocol: TCP
      selector:
        run: my-master
    -------------
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: my-master
    spec:
      selector:
        matchLabels:
          run: my-master
      replicas: 1
      template:
        metadata:
          labels:
            run: my-master
        spec:
          containers:
          - name: mongomaster
            image: yourcoolimage:lates
            ports:
            - containerPort: #your-port-exposed-in-pod
    

    此外,您可以为所有只读副本使用一个服务,该服务将平衡所有副本之间的请求。

    apiVersion: v1
    kind: Service
    metadata:
      name: my-replicas
      labels:
        run: my-replicas
    spec:
      type: LoadBalancer
      ports:
      - port: #your-external-port
        targetPort: #your-port-exposed-in-pod
        protocol: TCP
      selector:
        run: my-replicas
    
    ---------
    
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: my-replicas
    spec:
      selector:
        matchLabels:
          run: my-replicas
      replicas: 2
      template:
        metadata:
          labels:
            run: my-replicas
        spec:
          containers:
          - name: mongoreplica
            image: yourcoolimage:lates
            ports:
            - containerPort: #your-port-exposed-in-pod
    

    出于安全原因,我还建议您不要将 Pod 暴露在您的网络之外。最好创建严格的防火墙规则来限制任何意外连接。

    【讨论】:

    • 感谢您的回答,基于选举的拓扑怎么样,集合中的任何成员都可以在某个时候成为主控?
    • 在这种情况下,您需要为每个节点创建服务,每个节点可以作为主或副本
    猜你喜欢
    • 2021-12-21
    • 2017-02-13
    • 2020-04-25
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 2020-06-15
    相关资源
    最近更新 更多