2
votes

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
I would say you should add initContainer to your microservice, which would search for the DB, and when it's gonna be ready, then deploy the microservice. 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.Jakub
thank you, does initContainer works only within the pod where it's called? Or can init a container at another pod?J.J. Beam
I'm not sure what you mean by that, Init Containers are containers that run before the main container runs, so you have to configure them in your application deployment, and they are able to e.g. nslookup the databse service. There is an example in above link which you should use as a reference.Jakub
Thank you! My question is quite simple: do the containers that run before the main container runs and the main container must be in the same pod?J.J. Beam
Yes, they have to be in the same pod. As init container gonna work unless, f.e. the database service will be unvaliable, then the main container is gonna start.Jakub

1 Answers

1
votes

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.