Connecting two containers with Kubernetes using environment variables

10/1/2020

I'm new to k8s and need some direction on how to troubleshoot.

I have a postgres container and a graphql container. The graphql container is tries to connect to postgres on startup.

Problem

The graphql container can't connect to postgres. This is the error on startup:

{"internal":"could not connect to server: Connection refused\n\tIs the server running on host \"my-app\" (xxx.xx.xx.xxx) and accepting\n\tTCP/IP connections on port 5432?\n", "path":"

quot;,"error":"connection error","code":"postgres-error"}

My understanding is that the graphql-container doesn't recognize the IP my-app (xxx.xx.xx.xxx). This is the actual Pod Host IP, so I'm confused as to why it doesn't recognize it. How do I troubleshoot errors like these?

What I tried

  • Hardcoding the host in the connection uri in deployment.yaml to the actual pod host IP. Same error.

  • Bashed into the graphql container and verified that it had the correct env values with the env command.

deployment.yaml

spec:
  selector:
    matchLabels:
      service: my-app
  template:
    metadata:
      labels:
        service: my-app
...
  - name: my-graphql-container
    image: image-name:latest
    env:
    - name: MY_POSTGRES_HOST
      value: my-app
    - name: MY_DATABASE
      value: db
    - name: MY_POSTGRES_DB_URL # the postgres connection url that the graphql container uses
      value: postgres://$(user):$(pw)@$(MY_POSTGRES_HOST):5432/$(MY_DATABASE)
...
  - name: my-postgres-db
    image: image-name:latest
-- tbd_
kubernetes
postgresql

1 Answer

10/2/2020

In k8s docs about pods you can read:

Pods in a Kubernetes cluster are used in two main ways:

  • Pods that run a single container. ...

  • Pods that run multiple containers that need to work together. ...

Note: Grouping multiple co-located and co-managed containers in a single Pod is a relatively advanced use case. You should use this pattern only in specific instances in which your containers are tightly coupled.

Each Pod is meant to run a single instance of a given application. ...


Notice that your deployment doesn't fit this descriprion because you are trying to run two applications in one pod.

Remember to always use one pod per container and only use multiple containers per pod if it's impossible to separate them (and for some reason they have to run together).

And the rest was already mentioned by David.

-- Matt
Source: StackOverflow