kuberneteskubernetes-service

How can I create a Kubernetes service which selects pods from another namespace?


In certain cases I want to redirect all traffic to my service to pods in another namespace. How can I do this?

I have these pod in my-namespace-1:

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
  namespace: my-namespace-1
  labels:
    app: my-app
spec:
  containers:
    - name: nginx
      image: nginx
      ports:
        - containerPort: 80

and service in my-namespace-2:

apiVersion: v1
kind: Service
metadata:
  name: my-service
  namespace: my-namespace-2
spec:
  selector:
    app: my-app
  ports:
    - name: http
      port: 80
      targetPort: 80
  type: ClusterIP

But when I call the service I get HTTP status 503 from the ingress controller I guess.

Do I need to set up an service in my-namespace-2 too? Or what else is missing?


Solution

  • The service cannot select pods in other namespaces. It can only select pods in its own namespace, but question is why cant you create a service in the other namespace directly?

    As a workaround, what you can do is create a service my-service in my-namespace-1 as well and proxy from service in my-namespace-2 e.g. create the service in my-namespace-2 like this

    kind: Service
    apiVersion: v1
    metadata:
      name: my-service
      namespace: my-namespace-2
    spec:
      type: ExternalName
      externalName: my-service.my-namespace-1.svc.cluster.local
      ports:
      - port: 80