Is there a way to two containers with same app connect to same DB on Kubernetes?

7/24/2018

I need to run two "instances" of an application, but they should access the same DB, and I need it to be run on my Kubernetes cluster, so I can provide multi-AZ access to users.

Is it possible to be achieved on Kubernetes? Do I need StatefulSets? And, more important, is it possible to manage the DB pod with Kubernetes?

-- Pedro Henrique
distributed-system
kubernetes

1 Answer

7/24/2018

I need to run two "instances" of an application, but they should access the same DB, and I need it to be run on my Kubernetes cluster, so I can provide multi-AZ access to users.

This really depends on what you mean by instances. The recommended way is to create a deployment with replicas: 2 like so:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    run: my_app
  name: my_app
spec:
  replicas: 2
  selector:
    matchLabels:
      run: my_app
  template:
    metadata:
      labels:
        run: my_app
    spec:
      containers:
      - image: my_app:version
        name: my_app

This will ensure you have 2 "instances" of the app.

If you need to run 2 "instances" with differing configuration, you might choose to do two distinct deployments, and change the names and labels on them:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    run: my_app_1
  name: my_app_1
spec:
  replicas: 1
  selector:
    matchLabels:
      run: my_app_1
  template:
    metadata:
      labels:
        run: my_app_1
    spec:
      containers:
      - image: my_app:version
        name: my_app_1

Connecting these two instances to the database is fairly easy, you'd just pass your database connection string as a configuration option to the database. It can live inside or outside the cluster.

Do I need StatefulSets?

You only need statefulsets if your app needs to have predictable names, and stores state in some manner.

And, more important, is it possible to manage the DB pod with Kubernetes?

It is entirely possible to run the database inside the cluster. Whether it's a good idea to do so is up to you.

Databases are not traditionally very good at unexpected outages. With Kubernetes, it's possible the database pod could be moved at any time, and this could cause an issue for your app, or database.

You'll need to configure some kind of reattachable storage using a persistent volume but even then, there's no guarantee your db will be resistent to Kubernetes restarting it and restarting the database.

There are databases designed to run more successfully in Kubernetes, such as Vitess which may solve your problem.

-- jaxxstorm
Source: StackOverflow