DEV Community

George Pamfilis
George Pamfilis

Posted on

How to connect an external database to Kubernetes for a flask deployment.

The Problem.

I created a database on digital ocean and because I do not want to create a Kubernetes postgress database with persistent volumes and claims. I must connect to this External Service.

Digital ocean gave me this connection string for my SQLALCHEMY_URI

postgresql://user:password@hostname:25061/databasename?sslmode=require

It works with docker-compose and non docker flask run.

For Kubernetes though it complains that it cannot resolve the hostname.

We will rename the hostnameto digitaloceanpostgress. It can be anything. It must match the
service.yml
further down though.

So our deployment will look something like this. This is mine, yours could be different.

apiVersion: apps/v1 #  for k8s versions before 1.9.0 use apps/v1beta2  and before 1.8.0 use extensions/v1beta1
kind: Deployment
metadata:
  name: backend-deployment
  labels:
    app: backend-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: backend-deployment
  template:
    metadata:
      labels:
        app: backend-deployment
    spec:
      containers:
      - name: backend-deployment
        image: username/yourflaskserveretc:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 8080
        env:
        - name: SQLALCHEMY_DATABASE_URI
        # Set this as a secret.
          value: "postgresql://user:password@digitaloceanpostgress:25061/databasename?sslmode=require"
Enter fullscreen mode Exit fullscreen mode

Setting up the service.

Type in your terminal $ nslookup hostname (something.com) and paste the ip in the service.yml bellow.

kind: Service
apiVersion: v1
metadata:
  name: digitaloceanpostgress
spec:
  clusterIP: None
  ports:
  - port: 25061
---
kind: Endpoints
apiVersion: v1
metadata:
  name: digitaloceanpostgress
subsets:
  - addresses:
  # nslookup hostname given by digitalocean database.
      - ip: ip-from-nslookup
    ports:
      - port: 25061
        name: digitaloceanpostgress
Enter fullscreen mode Exit fullscreen mode

Finito.

Disclaimer. Although this works for me it might not be the goto solution for a pro. I am still a newbie.

References.

Top comments (0)