<p>I using Kubernetes 1.12. I have a service (e.g. pod) which may have multiple instances (e.g. replicas > 1)</p>

<p>My goal is to perform a maintenance task (e.g. create\upgrade database, generate certificate, etc) <strong>before</strong> any of service instances are up.</p>

<p>I was considering to use Init Container, but at least as I understand, Init Container will be executed anytime additional replica (pod) is created and worse - that might happen in parallel. In that case, multiple Init Containers might work in parallel and thus corrupt my database and everything else.</p>

<p>I need a clear solution to perform a bootstrap maintenance task <strong>only once</strong> per deployment. How you would suggest to do that?</p>

<p>I encountered the <a href="https://stackoverflow.com/a/57269987/1763012">same problem</a> running db migrations before each deployment. Here's a solution based on a Job resource:</p>

<pre class="lang-sh prettyprint-override"><code>kubectl apply -f migration-job.yml 
kubectl wait --for=condition=complete --timeout=60s job/migration
kubectl delete job/migration
kubectl apply -f deployment.yml
</code></pre>

<p><code>migration-job.yml</code> defines a <a href="https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/" rel="nofollow noreferrer">Job</a> configured with <code>restartPolicy: Never</code> and a reasonably low <code>activeDeadlineSeconds</code>. Using <code>kubectl wait</code> ensures that any errors or timeout in <code>migration-job.yml</code> causes the script to fail and thus prevent applying <code>deployment.yml</code>.</p>
