Answer a question

I am trying to connect a pod which is running in Kind with a local Postgres database which runs in a Docker container. I tried to add the following service but the pod still cannot connect when using the DNS name postgres.dev.svc.

kind: Service
apiVersion: v1
metadata:
  name: postgres
  namespace: dev
spec:
  type: ExternalName
  externalName: 10.0.2.2

Is there another way to connect these two components?

Answers

First of all it's not the correct usage of the ExternalName service type. Although putting an IP address in externalName field it's perfectly feasible i.e. the resource will be created and you won't get any complaint from kubernetes API server. ❗But this value is treated as a domain name, comprised of digits, not as an IP adress. You can read about it in the official kubernetes docs:

Note: ExternalName accepts an IPv4 address string, but as a DNS names comprised of digits, not as an IP address. ExternalNames that resemble IPv4 addresses are not resolved by CoreDNS or ingress-nginx because ExternalName is intended to specify a canonical DNS name. To hardcode an IP address, consider using headless Services.

So what you really need here is Service without a selector:

Services most commonly abstract access to Kubernetes Pods, but they can also abstract other kinds of backends. For example:

  • You want to have an external database cluster in production, but in your test environment you use your own databases.
  • You want to point your Service to a Service in a different Namespace or on another cluster.
  • You are migrating a workload to Kubernetes. While evaluating the approach, you run only a portion of your backends in Kubernetes.

In any of these scenarios you can define a Service without a Pod selector. For example:

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  ports:
    - protocol: TCP
      port: 80
      targetPort: 9376

Because this Service has no selector, the corresponding Endpoints object is not created automatically. You can manually map the Service to the network address and port where it's running, by adding an Endpoints object manually:

apiVersion: v1
kind: Endpoints
metadata:
  name: my-service
subsets:
  - addresses:
      - ip: 192.0.2.42
    ports:
      - port: 9376

In your particular case your Service definition may look as follows:

apiVersion: v1
kind: Service
metadata:
  name: postgres
spec:
  ports:
    - protocol: TCP
      port: 5432
      targetPort: 5432

and the corresponding Endpoints object may look like this:

apiVersion: v1
kind: Endpoints
metadata:
  name: postgres
subsets:
  - addresses:
      - ip: 10.0.2.2
    ports:
      - port: 5432

Of course the IP address 10.0.2.2 must be reachable from within your kubernetes cluster.

Logo

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

更多推荐