I wanna run a microservice which use DB. DB need to deploy in the same kubernetes cluster as well using PVC/PV. What is the kubernetes service name/command to use to implement such logic:

  1. Deploy the DB instance
  2. If 1 is successful, then deploy the microservice, else return to 1 and try (if 100 times fail - then stop and alarm)
  3. If 2 is successful, use work with it, autoscale if needed (autoscale kubernetes option)

I concern mostly about 1-2: the service cannot work without the DB, but at the same time need to be in different pods ( or am I wrong and it's better to put 2 containers: DB and service at the same pod?)

1

There are 1 answers

0
Jakub On BEST ANSWER

I would say you should add initContainer to your microservice, which would search for the DB service, and whenever it's gonna be ready, then the microservice will be started.

e.g.

apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app: myapp
spec:
  containers:
  - name: myapp-container
    image: busybox:1.28
    command: ['sh', '-c', 'echo The app is running! && sleep 3600']
  initContainers:
  - name: init-mydb
    image: busybox:1.28
    command: ['sh', '-c', "until nslookup mydb.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for mydb; sleep 2; done"]

As for the command simply use the kubectl apply with your yamls (with initContainer configured in your application).

If you want to do that in more automative way you can think about using fluxCD/argoCD.


As for the question from comments, containers that run before the main container runs and the main container must be in the same pod?

Yes, they have to be in the same pod. As the init container is going to work unless, f.e. the database service will be avaliable, then the main container is gonna start. There is great example with that in above initContainer documentation.