Kubernetes K8S之Pod跨namespace名称空间访问Service服务

Kubernetes的两个Service(ServiceA、ServiceB)和对应的Pod(PodA、PodB)分别属于不同的namespace名称空间,现需要PodA和PodB跨namespace名称空间并通过Service实现互访。应该如何实现?

场景需求

Kubernetes的两个Service(ServiceA、ServiceB)和对应的Pod(PodA、PodB)分别属于不同的namespace名称空间,现需要PodA和PodB跨namespace名称空间并通过Service实现互访。如何实现?

说明:这里是指通过Service的Name进行通信访问,而不是通过Service的IP【因因为每次重启Service,NAME不会改变,而IP是会改变的】。

主机配置规划

服务器名称(hostname) 系统版本 配置 内网IP 外网IP(模拟)
k8s-master CentOS7.7 2C/4G/20G 172.16.1.110 10.0.0.110
k8s-node01 CentOS7.7 2C/4G/20G 172.16.1.111 10.0.0.111
k8s-node02 CentOS7.7 2C/4G/20G 172.16.1.112 10.0.0.112

创建Service和Pod

相关yaml文件

[root@k8s-master cross_ns]# pwd
/root/k8s_practice/cross_ns
[root@k8s-master cross_ns]# 
[root@k8s-master cross_ns]# cat deply_service_myns.yaml 
apiVersion: v1
kind: Namespace
metadata:
  name: myns
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deploy1
  namespace: myns
spec:
  replicas: 2
  selector:
    matchLabels:
      app: myapp
      release: v1
  template:
    metadata:
      labels:
        app: myapp
        release: v1
    spec:
      containers:
      - name: myapp
        image: registry.cn-beijing.aliyuncs.com/google_registry/myapp:v1
        imagePullPolicy: IfNotPresent
        ports:
        - name: http
          containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: myapp-clusterip1
  namespace: myns
spec:
  type: ClusterIP  # 默认类型
  selector:
    app: myapp
    release: v1
  ports:
  - name: http
    port: 80
    targetPort: 80

[root@k8s-master cross_ns]# 
[root@k8s-master cross_ns]# cat deply_service_mytest.yaml 
apiVersion: v1
kind: Namespace
metadata:
  name: mytest
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deploy2
  namespace: mytest
spec:
  replicas: 2
  selector:
    matchLabels:
      app: myapp
      release: v2
  template:
    metadata:
      labels:
        app: myapp
        release: v2
    spec:
      containers:
      - name: myapp
        image: registry.cn-beijing.aliyuncs.com/google_registry/myapp:v2
        imagePullPolicy: IfNotPresent
        ports:
        - name: http
          containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: myapp-clusterip2
  namespace: mytest
spec:
  type: ClusterIP  # 默认类型
  selector:
    app: myapp
    release: v2
  ports:
  - name: http
    port: 80
    targetPort: 80

运行yaml文件

kubectl apply -f deply_service_myns.yaml 
kubectl apply -f deply_service_mytest.yaml

查看myns名称空间信息

[root@k8s-master cross_ns]# kubectl get svc -n myns -o wide
NAME               TYPE 

你可能感兴趣的:(kubernetes,ci/cd,devops,kubernetes,k8s,devops,ci/cd,docker)