Friends, I am learning here and trying to implement an init container which checks if MySQL is ready for connections. I have a pod running MySQL and another pod with an app which will connect to the MysSQL pod when its ready.
No success so far. The error I am getting is the following: sh: mysql: not found. This is how I am trying:
initContainers:
- name: {{ .Values.initContainers.name }}
image: {{ .Values.initContainers.image }}
command:
- "sh"
- "-c"
- "until mysql --host=mysql.default.svc.cluster.local --user={MYSQL_USER}
--password={MYSQL_PASSWORD} --execute=\"SELECT 1;\"; do echo waiting for mysql; sleep 2; done;"
Any idea how I could make this work?
Do absolutely nothing; even delete the initContainers: you have now.
Let's say your application starts up before the database is ready. It tries to connect, fails, and exits. Kubernetes notices this, so it will try to start the application again; if it fails repeatedly, it will start waiting progressively longer between retries (you will see CrashLoopBackOff state). Eventually the cluster will have waited long enough that the database is ready, and the next retry will be successful.
Note that this is probably the same thing that will happen if the database restarts after the application is already running; "at startup time" doesn't need to be a special case.
Please try using this.
initContainers:
- name: init-cont
image: busybox:1.31
command: ['sh', '-c', 'echo -e "Checking for the availability of MySQL Server deployment"; while ! nc -z mysql 3306; do sleep 1; printf "-"; done; echo -e " >> MySQL DB Server has started";']
Your initContainer is missing the mysql client binary.
There are a few ways to solve this:
Assuming Alpine is your base image you would have a dockerfile like this:
FROM alpine:3.14
RUN apk add mysql-client
Then your initContainer command would be:
command:
- "/bin/ash"
- "-c"
- "until mysql --host=mysql.default.svc.cluster.local --user={MYSQL_USER}
--password={MYSQL_PASSWORD} --execute=\"SELECT 1;\"; do echo waiting for mysql; sleep 2; done;"
My recommendation, use the official mysql docker image