PostgreSQL and Microk8s
This is a guide to how you can connect to PostgreSQL from Microk8s pods. I will be using Ubuntu server 20.04, Postgres 12 and mircok8s version 1.18.4.
Install#
Get Microk8s using snap:
snap install microk8s --classic
Get PostgreSQL using apt:
sudo apt install postgresql postgresql-contrib
Configure#
Before we can connect to the PostgreSQL instance we need to start a cluster and enable some addons, and configure postgres to listen for connections from Microk8s.
Microk8s addons#
Create a Microk8s cluster with microk8s.start
and enable the DNS and Host-access addons.
microk8s.enable dns host-access
Host-access will bind the Host to an IP within your cluster, the default being 10.0.1.1
Postgresql config#
The main config for PostgreSQL will be found at /etc/postgresql/<version>/main/postgresql.conf
Open this with the editor of your choice and navigate to the ‘CONNECTIONS AND AUTHENTICATION’ section. Here we need to change the listen_addresses
to listen for connections on the IP address of the Host in the cluster. To do this, append the IP returned when we enabled host-access (10.0.1.1
) to the listen_addresses separated by a comma.
listen_addresses = 'localhost,10.0.1.1'
Next we have to add the IP range of our pods to pg_hba.conf
to allow connections from our Microk8s cluster. Micrk8s uses flannel for networking, and we can find the subnet it is using by looking at /var/snap/microk8s/common/run/flannel/subnet.env
and copying the value of FLANNEL_SUBNET. Add this to the pg_hba.conf file in the same folder as the main PostgreSQL config.
# IPv4 local connections:
host all all 127.0.0.1/32 md5
host all all 10.1.15.1/24 md5 # Micrk8s network
Don’t forget to restart PostgreSQL with
sudo systemctl restart postgresql
To connect we will also need to set a password. For this tutorial we will use the default user (postgres
).
$ sudo -u postgres psql # Connect to Postgres using Linux posgres user
> \password # Set a password for network connections
Kubernetes Resources#
Now that we have configured PostgreSQL to allow connections from Microk8s, and we have an IP address of our host configured in the Kubernetes network, we have to create the endpoint and service for our applications to use:
kind: Service
apiVersion: v1
metadata:
name: postgres
spec:
type: ClusterIP # Probably don't want to expose it outside of the cluster
ports:
- port: 5432
targetPort: 5432
---
kind: Endpoints
apiVersion: v1
metadata:
name: postgres
subsets:
- addresses:
- ip: 10.0.1.1 # Host IP from host-access
ports:
- port: 5432
You can now connect to Postgres from a pod at
postgres://<username>:<password>@postgres:5432/<table_name>?sslmode=disable`