trying to open Postgres port 5432
so it can be accessible from my local machine. the port is only open from kubernetes pods.
127.0.0.1:5432 <====> kubernetes-pod <=====> Postgres Server
basically I want to make port 5432 accessible via my local machine, the port is only accessible from kubernetes-pod. how do I do that.
I tried which I think this would work if postgres server is running on the same pod which is not in my case:
kubectl port-forward pod-5bf5c7df9b-xcjsf 5433:5432
Note: The PostgreSQL server runs as standalone db server and only the pod can access the port and I want to access the PostgreSQL db port from my local machine .
CodePudding user response:
Try this:
kubectl port-forward -n <namespace-name> pod/pod-5bf5c7df9b-xcjsf 5432:5432
Note the differences:
- Namespace needs to be specified if not
default
- I usually prefix the pod name with
pod/
- The local port 5432 connects to the k8s cluster on port 5432
In addition, it's best practice to port-forward to the service instead of the pod. For example: kubectl port-forward -n namespace svc/service-name 5432:5432
since pod names change but the service name does NOT. And, remember that the service port is usually 5432 but the pod may not listen on that port.
I hope this helps. I work for CodeZero and we allow you to easily connect with cluster resources with our teleport feature. Check it out at https://codezero.io
You can also use CodeZero CLI (czctl) to teleport into the cluster and then you can access kubernetes resources locally:
czctl start
czctl namespace teleport <namespace-name>
Then, as long as you have a Service in the cluster pointing to Postgres, you can access that service as if it's running locally on your computer. For example:
Create a Service called my-postgres-db
which points to your Postgress Pod/Deployment/ReplicaSet pods. Then you can connect using
psql -h my-postgres-db ...
CodePudding user response:
The easiest and best way to accomplish this is using socat
in a pod.
You can use the alpine/socat
container image to create the pod. Then use port-forward into this pod which will forward the connections to the target db.
Here are the steps:
- Create a file
my-postgresql-socat.yaml
:
apiVersion: v1
kind: Pod
metadata:
name: my-postgresql-socat
labels:
name: my-postgresql-socat
spec:
containers:
- name: my-postgresql-socat
image: alpine/socat
command: ["socat", "-dd", "tcp4-listen:5432,fork,reuseaddr", "tcp4:my-postgresql-host:5432"]
resources:
limits:
memory: "64Mi"
cpu: "50m"
ports:
- containerPort: 5432
- Create a pod with
kubectl apply -f my-postgresql-socat.yaml
- Run a local port-forward:
oc port-forward my-postgresql-socat 5432:5432
You can access your database now via localhost:5432
- When finished, delete the pod:
kubectl delete pod my-postgresql-socat