concept init container in category microservice

This is an excerpt from Manning's book Microservices Security in Action.
In Kubernetes, we can run more than one container in a Pod, but as a practice, we run only one application container. Along with an application container, we can also run one or more init containers. If you’re familiar with Java (or any other programming language), an init container in Kubernetes is like a constructor in a Java class. Just as the constructor in a Java class runs well before any other methods, an init container in a Pod must run and complete before any other application containers in the Pod start.
This is a great way to initialize a Kubernetes Pod. You can pull any files (keystores, policies, and so forth), configurations, and so on with an init container. Just as with any other application container, we can have more than one init container in a given Pod; but unlike an application container, each init container must run to completion before the next init container starts.
Listing 11.9 modifies the STS Deployment to load keystore.jks and jwt.jks files from a Git repository by using an init container instead of loading them from a ConfigMap object (as in listing 11.8). You can find the complete updated definition of the Kubernetes Deployment in the chapter11/sample01/sts.deployment.with.initcontainer.yaml file. The following listing shows part of the updated STS deployment, corresponding to the init container.
initContainers: #1 - name: init-keystores image: busybox:1.28 #2 command: #3 - "/bin/sh" - "-c" - "wget ...sample01/keystores/jwt.jks \ -O /opt/jwt.jks | wget ...sample01/keystores/keystore.jks \ -O /opt/keystore.jks" volumeMounts: #4 - name: keystore #5 mountPath: "/opt/keystore.jks" #6 subPath: "keystore.jks" #7 - name: jwt-keystore subPath: "jwt.jks"We’ve created the init container with the
busyboxDocker image. Because thebusyboxcontainer is configured as an init container, it runs before any other container in the Pod. Under thecommandelement, we specified the program thebusyboxcontainer should run. There we got both keystore.jks and jwt.jks files from a Git repo and copied both keystore.jks and jwt.jks files to the /opt directory of thebusyboxcontainer filesystem.The whole objective of the init container is to get the two keystores into the Docker container that runs the STS. To do that, we need to have two volume mounts; both volumes (
keystoreandjwt-keystore) are mapped to the /opt directory. Because we already have volume mounts with these two names (under thesecure-stscontainer in the following listing), the two keystores are also visible to thesecure-stscontainer filesystem.