Postgres deploy using Kubernetes not working

3/31/2020

I am new to Azure Kubernetes Service (AKS), I created the deployment file for postgres as follow

kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: postgres-pv-claim
  labels:
    app: postgres
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 5Gi

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: postgres
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
        - name: postgres
          image: postgres:xx.xx
          imagePullPolicy: "IfNotPresent"
          ports:
            - containerPort: 5432
          env:
            - name: POSTGRES_DB
                value: postgresdb
            -   name: POSTGRES_USER
                value: postgresadmin
            - name: POSTGRES_PASSWORD
                value: admin123
          volumeMounts:
            - mountPath: /var/lib/postgresql/data
              name: postgredb
      volumes:
        - name: postgredb
          persistentVolumeClaim:
            claimName: postgres-pv-claim

apiVersion: v1
kind: Service
metadata:
  name: postgres
  labels:
    app: postgres
spec:
  type: NodePort
  ports:
   - port: 5432
  selector:
   app: postgres

and after deploying the postgres service on AKS, service got created.

abc@Azure:~$ kubectl get svc
NAME         TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE
kubernetes   ClusterIP   10.0.0.1       <none>        443/TCP          6h45m
postgres     NodePort    10.0.165.161   <none>        5432:30692/TCP   9m8s

But when I tried to get into the PSQL by using psql -h localhost -U postgresadmin --password -p 30692 postgresdb, it shows that connection refused.

abc@Azure:~$ psql -h localhost -U postgresadmin --password -p 30692 postgresdb
Password:
psql: error: could not connect to server: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 30692?
could not connect to server: Connection refused
        Is the server running on host "localhost" (127.0.0.1) and accepting
        TCP/IP connections on port 30692?
-- Ravindra Gupta
azure-aks
azure-devops
docker
kubernetes
postgresql

1 Answer

3/31/2020

For your issue, it seems you want to expose the PostgreSQL to the Internet. As I see you made two mistakes.

First is the YMAL file, you need to change the service into below:

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

The second is that the connect command. I think you connect the PostgreSQL in the Azure cloud shell, so you need to use the external IP of the service to connect:

psql -h external-IP -U postgresadmin --password -p 5432 postgresdb
-- Charles Xu
Source: StackOverflow