HowTo: Get postgres shell in kubernetes

If your postgres database is only accessible from inside a kubernetes cluster, e.g. if it's configured in AWS RDS and not available to the public (as it should be!), here's how to open a psql shell inside Kubernetes and connect to the database. Make sure to replace the variables appropriately.

$ kubectl run postgresql-client \
  --image=postgres      \
  --namespace=$NAMESPACE \
  --stdin=true --tty=true \
  --rm=true                \
  --env="PGPASSWORD=$PASSWORD_FOR_POSTGRES \
  --command -- \
  psql --host=$HOSTNAME_FOR_POSTGRES --username=$USERNAME_FOR_POSTGRES $DATABASE_FOR_POSTGRES

You need to specify the password as an env variable for the container since you can't answer the password prompt in the container.

If you don't immediately see a postgres shell, wait a few seconds and press enter.

The pod will automatically be deleted when the shell closes.

Florian Heinle Over 1 year ago