Skip to content

[PostgreSQL connection in Kubernetes] #417

Description

@youssef-ham

Course

ai-dev-tools-zoomcamp

Question

When deploying Agent Relay and PostgreSQL from Docker Compose to a local kind Kubernetes cluster, why does Agent Relay fail to connect to PostgreSQL when the database host is set to localhost, and what should be changed?

Answer

localhost refers to the current container/pod, not to another Kubernetes service. Therefore, when Agent Relay runs in its own pod, setting the PostgreSQL host to localhost makes it try to find PostgreSQL inside the Agent Relay container.

The solution is to expose PostgreSQL through a Kubernetes Service and use the Service DNS hostname as the database host.

For example, if the PostgreSQL Service is named:

apiVersion: v1
kind: Service
metadata:
  name: postgres
spec:
  selector:
    app: postgres
  ports:
    - port: 5432
      targetPort: 5432

Agent Relay should connect using:

postgres:5432

instead of:

localhost:5432

The PostgreSQL connection configuration should therefore use the Kubernetes Service name, for example:

postgresql://<user>:<password>@postgres:5432/<database>

After applying the Kubernetes manifests, the connection can be verified from the Agent Relay pod with:

kubectl get pods
kubectl get services
kubectl logs deployment/agent-relay

This is different from Docker Compose, where the Compose service name can also be used for container-to-container communication. In Kubernetes, the equivalent mechanism is the Kubernetes Service and its DNS name.

For a local kind cluster, the Agent Relay image also needs to be available inside the cluster. If the image is built locally, it can be loaded with:

docker build -t agent-relay:local .
kind load docker-image agent-relay:local

Then the Kubernetes Deployment can reference:

image: agent-relay:local
imagePullPolicy: IfNotPresent

This allows the locally built Agent Relay image to run in kind without requiring the image to be pushed to a remote registry.

Checklist

  • I have searched existing FAQs and this question is not already answered
  • The answer provides accurate, helpful information
  • I have included any relevant code examples or links

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions