Introduction
During my working day, I was confronting to a simple developer question:
👉 How to connect my local API server to a remote RDS Postgres instance present into an AWS VPC, accessible only throug the Kubernetes (k8s) cluster?
Kubernetes is an open-source platform for automating deployment, scaling, and management of containerized applications. It provides a container-centric infrastructure, orchestrating the deployment and management of application containers across clusters of hosts. Kubernetes abstracts away much of the complexity involved in managing containerized applications, allowing for efficient resource utilization and seamless scaling.
Two steps to follow to create you database tunnel
To connect you from your local environment to your remote database through a Kubernetes service, you just need to:
1. Create a passthrough service:
This proxy service will be essential to reach you database.
Its target is to forward all incoming trafic from the port 5432 to the port 5432 of the PostgresSQL server (a simple tunnel, like an SSH tunnel).In this example, we’ll connect to a RDS PostgresSQL server, but this approach also works with all types of services : Redis, Mysql, MariaDB etc..
1 2 |
$ export DATABASE_PORT=5432 $ export DATABASE_HOSTNAME=example.eu-west-1.rds.amazonaws.com |
Then,
1 |
$ kubectl run postgres-tunnel --image=alpine/socat -it --tty --rm --expose=true --port={DATABASE_PORT} tcp-listen:{DATABASE_PORT},fork,reuseaddr tcp-connect:{DATABASE_HOSTNAME}:{DATABASE_PORT} |
This command creates a k8S service named postgres-tunnel based on the alpine/socat:lastest image (you can use your own) and forward all incoming trafic to the RDS database. It’s our pass-through.
2. Connect you on the database:
You now have a pass-through, you can simply connect you to your database. 🎉
1 |
$ psql postgres://USERNAME:PASSWORD@localhost:5432/schema_name |
Sources
- Kubernetes: Official documentation
Leave a comment