<p>I have K8s used by Helm 3.</p>
<ol>
<li>I need to access a k8s job while running in yaml file (created by helm).</li>
</ol>
<p>The kubectl version:</p>
<blockquote>
<p>Client Version: version.Info{Major:&quot;1&quot;, Minor:&quot;21&quot;,
GitVersion:&quot;v1.21.6&quot;,
GitCommit:&quot;d921bc6d1810da51177fbd0ed61dc811c5228097&quot;,
GitTreeState:&quot;clean&quot;, BuildDate:&quot;2021-10-27T17:50:34Z&quot;,
GoVersion:&quot;go1.16.9&quot;, Compiler:&quot;gc&quot;, Platform:&quot;linux/amd64&quot;} Server
Version: version.Info{Major:&quot;1&quot;, Minor:&quot;21&quot;, GitVersion:&quot;v1.21.6&quot;,
GitCommit:&quot;d921bc6d1810da51177fbd0ed61dc811c5228097&quot;,
GitTreeState:&quot;clean&quot;, BuildDate:&quot;2021-10-27T17:44:26Z&quot;,
GoVersion:&quot;go1.16.9&quot;, Compiler:&quot;gc&quot;, Platform:&quot;linux/amd64&quot;}</p>
</blockquote>
<p>Helm version:</p>
<blockquote>
<p>version.BuildInfo{Version:&quot;v3.3.4&quot;,
GitCommit:&quot;a61ce5633af99708171414353ed49547cf05013d&quot;,
GitTreeState:&quot;clean&quot;, GoVersion:&quot;go1.14.9&quot;}</p>
</blockquote>
<p>As the following link:
<a href="https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#:%7Edcm-bot-890c06f7dff54e2d9d35332364e37a4f" rel="nofollow noreferrer">DNS concept</a></p>
<p>It works fine for Pod, <strong>but not for job</strong>.</p>
<p>As explained, for putting hostname and subdomain in Pod's YAML file, and add service that holds the domain...</p>
<ol start="2">
<li>Need to check the state if running.</li>
</ol>
<p>for pod, it is ready state.</p>
<pre><code>kubectl wait pod/pod-name --for=condition=ready ...
</code></pre>
<p>For job there is no ready state (while pod behind is running).</p>
<p>How can I check the state of pod behind the job (job is running) and how can I use host + subdomain for jobs?</p>
<p>My code ...
(I removed some security tags, but the same. Important - It may be complicated.</p>
<p>I create a listener - running when listen, with job that need to do some curl command, and this can be achieved whether it has access to that pod behind the job):</p>
<p><strong>Listener (the pod is the last job):</strong></p>
<p>What I added is hostname and subdomain (which work for Pod, and not for Job). If it ever was on Pod - no problem.</p>
<p>I also realized that the name of the Pod (created by the job) has a hash automatic extension.</p>
<pre><code>apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include &quot;my-project.fullname&quot; . }}-listener
  namespace: {{ .Release.Namespace }}
  labels:
    name: {{ include &quot;my-project.fullname&quot; . }}-listener
    app: {{ include &quot;my-project.fullname&quot; . }}-listener
    component: {{ .Chart.Name }}
    subcomponent: {{ .Chart.Name }}-listener
  annotations:
    &quot;prometheus.io/scrape&quot;: {{ .Values.prometheus.scrape | quote }}
    &quot;prometheus.io/path&quot;: {{ .Values.prometheus.path }}
    &quot;prometheus.io/port&quot;: {{ .Values.ports.api.container | quote }}
spec:
  template: #PodTemplateSpec (Core/V1)
    spec: #PodSpec (core/v1)
      hostname: {{ include &quot;my-project.fullname&quot; . }}-listener
      subdomain: {{ include &quot;my-project.fullname&quot; . }}-listener-dmn
      initContainers:
        # twice - can add in helers.tpl
        - name: wait-mysql-exist-pod
          image: {{ .Values.global.registry }}/{{ .Values.global.k8s.image }}:{{ .Values.global.k8s.tag | default &quot;latest&quot; }}
          imagePullPolicy: IfNotPresent
          env:
            - name: MYSQL_POD_NAME
              value: {{ .Release.Name }}-mysql
            - name: COMPONENT_NAME
              value: {{ .Values.global.mysql.database.name }}
          command:
            - /bin/sh
          args:
            - -c
            - |-
              while [ &quot;$(kubectl get pod $MYSQL_POD_NAME 2&gt;/dev/null | grep $MYSQL_POD_NAME | awk '{print $1;}')&quot; \!= &quot;$MYSQL_POD_NAME&quot; ];do
                echo 'Waiting for mysql pod to be existed...';
                sleep 5;
              done
        - name: wait-mysql-ready
          image: {{ .Values.global.registry }}/{{ .Values.global.k8s.image }}:{{ .Values.global.k8s.tag | default &quot;latest&quot; }}
          imagePullPolicy: IfNotPresent
          env:
            - name: MYSQL_POD_NAME
              value: {{ .Release.Name }}-mysql
          command:
            - kubectl
          args:
            - wait
            - pod/$(MYSQL_POD_NAME)
            - --for=condition=ready
            - --timeout=120s
        - name: wait-mysql-has-db
          image: {{ .Values.global.registry }}/{{ .Values.global.k8s.image }}:{{ .Values.global.k8s.tag | default &quot;latest&quot; }}
          imagePullPolicy: IfNotPresent
          env:
            {{- include &quot;k8s.db.env&quot; . | nindent 12 }}
            - name: MYSQL_POD_NAME
              value: {{ .Release.Name }}-mysql
          command:
            - /bin/sh
          args:
            - -c
            - |-
             while [ &quot;$(kubectl exec $MYSQL_POD_NAME -- mysql -uroot -p$MYSQL_ROOT_PASSWORD -e 'show databases' 2&gt;/dev/null | grep $MYSQL_DATABASE | awk '{print $1;}')&quot; \!= &quot;$MYSQL_DATABASE&quot; ]; do
                echo 'Waiting for mysql database up...';
                sleep 5;
             done
      containers:
        - name: {{ include &quot;my-project.fullname&quot; . }}-listener
          image:  {{ .Values.global.registry }}/{{ .Values.image.repository }}:{{ .Values.image.tag | default &quot;latest&quot; }}
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          env:
          {{- include &quot;k8s.db.env&quot; . | nindent 12 }}
            - name: SCHEDULER_DB
              value: $(CONNECTION_STRING)
          command: {{- toYaml .Values.image.entrypoint | nindent 12 }}
          args: # some args ...
          ports:
            - name: api
              containerPort: 8081
          resources:
            limits:
              cpu: 1
              memory: 1024Mi
            requests:
              cpu: 100m
              memory: 50Mi
          readinessProbe:
            httpGet:
              path: /api/scheduler/healthcheck
              port: api
              scheme: HTTP
            initialDelaySeconds: 10
            periodSeconds: 5
            timeoutSeconds: 1
          livenessProbe:
            tcpSocket:
              port: api
            initialDelaySeconds: 120
            periodSeconds: 10
            timeoutSeconds: 5
          volumeMounts:
            - name: {{ include &quot;my-project.fullname&quot; . }}-volume
              mountPath: /etc/test/scheduler.yaml
              subPath: scheduler.yaml
              readOnly: true
      volumes:
      - name: {{ include &quot;my-project.fullname&quot; . }}-volume
        configMap:
          name: {{ include &quot;my-project.fullname&quot; . }}-config
      restartPolicy: Never
</code></pre>
<p>The service (for the subdomain):</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
  name: {{ include &quot;my-project.fullname&quot; . }}-listener-dmn
spec:
  selector:
    name: {{ include &quot;my-project.fullname&quot; . }}-listener
  ports:
    - name: api
      port: 8081
      targetPort: 8081
  type: ClusterIP
</code></pre>
<p>Roles + RoleBinding (to enable access for curl command):</p>
<pre><code>apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: {{ include &quot;my-project.fullname&quot; . }}-role
rules:
- apiGroups: [&quot;&quot;] # &quot;&quot; indicates the core API group
  resources: [&quot;pods&quot;]
  verbs: [&quot;get&quot;, &quot;watch&quot;, &quot;list&quot;, &quot;update&quot;]
- apiGroups: [&quot;&quot;] # &quot;&quot; indicates the core API group
  resources: [&quot;pods/exec&quot;]
  verbs: [&quot;create&quot;, &quot;delete&quot;, &quot;deletecollection&quot;, &quot;get&quot;, &quot;list&quot;, &quot;patch&quot;, &quot;update&quot;, &quot;watch&quot;]
- apiGroups: [&quot;&quot;, &quot;app&quot;, &quot;batch&quot;] # &quot;&quot; indicates the core API group
  resources: [&quot;jobs&quot;]
  verbs: [&quot;get&quot;, &quot;watch&quot;, &quot;list&quot;]

Role-Binding:
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: {{ include &quot;go-scheduler.fullname&quot; . }}-rolebinding
subjects:
- kind: ServiceAccount
  name: default
roleRef:
  kind: Role
  name: {{ include &quot;go-scheduler.fullname&quot; . }}-role
  apiGroup: rbac.authorization.k8s.io
</code></pre>
<p>And finally a tester that doing a curl command:</p>
<p>(For check I put <code>tail -f</code>), and enter the pod.</p>
<pre><code>apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include &quot;my-project.fullname&quot; . }}-test
  namespace: {{ .Release.Namespace }}
  labels:
    name: {{ include &quot;my-project.fullname&quot; . }}-test
    app: {{ include &quot;my-project.fullname&quot; . }}-test 
  annotations:
    &quot;prometheus.io/scrape&quot;: {{ .Values.prometheus.scrape | quote }}
    &quot;prometheus.io/path&quot;: {{ .Values.prometheus.path }}
    &quot;prometheus.io/port&quot;: {{ .Values.ports.api.container | quote }}
spec:
  template: #PodTemplateSpec (Core/V1)
    spec: #PodSpec (core/v1)
      initContainers:
        # twice - can add in helers.tpl
        #
        - name: wait-sched-listener-exists
          image: {{ .Values.global.registry }}/{{ .Values.global.k8s.image }}:{{ .Values.global.k8s.tag | default &quot;latest&quot; }}
          imagePullPolicy: IfNotPresent
          env:
            - name: POD_NAME
              value: {{ include &quot;my-project.fullname&quot; . }}-listener
          command:
            - /bin/sh
          args:
            - -c
            - |-
              while [ &quot;$(kubectl get job $POD_NAME 2&gt;/dev/null | grep $POD_NAME | awk '{print $1;}')&quot; \!= &quot;$POD_NAME&quot; ];do
                echo 'Waiting for scheduler pod to exist ...';
                sleep 5;
              done
        - name: wait-listener-running
          image: {{ .Values.global.registry }}/{{ .Values.global.k8s.image }}:{{ .Values.global.k8s.tag | default &quot;latest&quot; }}
          imagePullPolicy: IfNotPresent
          env:
            - name: POD_NAME
              value: {{ include &quot;my-project.fullname&quot; . }}-listener
          command:
            - /bin/sh
          args:
            - -c
            - |-
              while [ &quot;$(kubectl get pods 2&gt;/dev/null | grep $POD_NAME | awk '{print $3;}')&quot; \!= &quot;Running&quot; ];do
                echo 'Waiting for scheduler pod to run ...';
                sleep 5;
              done
      containers:
        - name: {{ include &quot;my-project.fullname&quot; . }}-test
          image:  {{ .Values.global.registry }}/{{ .Values.global.k8s.image }}:{{ .Values.global.k8s.tag | default &quot;latest&quot; }}
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          command:
            - /bin/sh
          args:
            - -c
            - &quot;tail -f&quot;
     # instead of above can be curl: &quot;curl -H 'Accept: application/json' -X get my-project-listener.my-project-listener-dmn:8081/api/scheduler/jobs&quot;

      restartPolicy: Never
</code></pre>
<p>I enter the test pod</p>
<pre><code>kubectl exec -it my-tester-&lt;hash&gt; -- /bin/sh
</code></pre>
<p>... and run the command:</p>
<pre><code>ping my-project-listener.my-project-listener-dmn
</code></pre>
<p>Got:</p>
<pre><code>ping: bad address 'my-project-listener.my-project-listener-dmn'
</code></pre>
<p>When doing that for pod:</p>
<blockquote>
<p>PING pod-hostname.pod-subdomain (): ... data bytes</p>
</blockquote>

Eitan
<p>There's a lot here, but I think you should be able to resolve all of this with a couple of small changes.</p>
<p>In summary, I'd suggest changing:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment     # &lt;-- not a Job
metadata: &amp;original-job-metadata-from-the-question
spec:
  template:
    metadata:
      labels:   # vvv matching the Service selector
        name: {{ include &quot;my-project.fullname&quot; . }}-listener
    spec:
      # delete all of the initContainers:
      containers: &amp;original-container-list-from-the-question
      volumes: &amp;original-volume-list-from-the-question
      # delete restartPolicy: (default value Always)
</code></pre>
<p>Delete the Role and RoleBinding objects; connect to the Service <code>http://my-project-listener-dmn:8081</code> and not an individual Pod; and you can <code>kubectl wait --for=condition=available</code> on the Deployment.</p>
<p><strong>Connect to Services, not individual Pods</strong> (or Jobs or Deployments).  The Service is named <code>{{ include &quot;my-project.fullname&quot; . }}-listener-dmn</code> and that is the host name you should connect to.  The Service acts as a very lightweight in-cluster load balancer, and will forward requests on to one of the pods identified by its selector.</p>
<p>So in this example you'd connect to the Service's name and port, <code>http://my-project-listener-dmn:8081</code>.  Your application doesn't answer the very-low-level ICMP protocol and I'd avoid <strong>ping</strong>(1) in favor of a more useful diagnostic.  Also consider setting the Service's port to the default HTTP port 80; it doesn't necessarily need to match the Pod's port.</p>
<p><strong>The Service selector needs to match the Pod labels</strong> (and not the Job's or Deployment's labels).  A Service attaches to Pods; a Job or a Deployment has a template to create Pods; and it's those labels that need to match up.  You need to add labels to the Pod template:</p>
<pre class="lang-yaml prettyprint-override"><code>spec:
  template:
    metadata:
      labels:
        name: {{ include &quot;my-project.fullname&quot; . }}-listener
</code></pre>
<p>Or, in a Helm chart where you have a helper to generate these labels,</p>
<pre class="lang-yaml prettyprint-override"><code>      labels: {{- include &quot;my-project.labels&quot; | nindent 8 }}
</code></pre>
<p>The thing to check here is <code>kubectl describe service my-project-listener-dmn</code>.  There should be a line at the bottom that says <code>Endpoints:</code> with some IP addresses (technically some individual Pod IP addresses, but you don't usually need to know that).  If it says <code>Endpoints: &lt;none&gt;</code> that's usually a sign that the labels don't match up.</p>
<p><strong>You probably want some level of automatic restarts.</strong>  A Pod can fail for lots of reasons, including code bugs and network hiccups.  If you set <code>restartPolicy: Never</code> then you'll have a Failed Pod, and requests to the Service will fail until you take manual intervention of some sort.  I'd suggest setting this to at least <code>restartPolicy: OnFailure</code>, or (for a Deployment) leaving it at its default value of <code>Always</code>.  (There is <a href="https://kubernetes.io/docs/concepts/workloads/controllers/job/#handling-pod-and-container-failures" rel="nofollow noreferrer">more discussion on Job restart policies</a> in the Kubernetes documentation.)</p>
<p><strong>You probably want a Deployment here.</strong>  A Job is meant for a case where you do some set of batch processing and then the job completes; that's part of why <code>kubectl wait</code> doesn't have the lifecycle option you're looking for.<br />
I'm guessing you want a Deployment instead.  With what you've shown here I don't think you need to make any changes at all besides</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment
</code></pre>
<p>Everything so far about Services and DNS and labels still applies.</p>
<p><strong>You can <code>kubectl wait</code> for a Deployment to be available.</strong>  Since a Job is expected to run to completion and exit, that's the state <code>kubectl wait</code> allows.  A Deployment is &quot;available&quot; if there is at least a minimum number of managed Pods running that pass their health checks, which I think is the state you're after.</p>
<pre class="lang-sh prettyprint-override"><code>kubectl wait --for=condition=available deployment/my-project-listener
</code></pre>
<p><strong>There are simpler ways to check for database liveness.</strong>  A huge fraction of what you show here is an involved sequence with special permissions to see if the database is running before the pod starts up.</p>
<p>What happens if the database fails while the pod is running?  One common thing that will happen is you'll get a cascading sequence of exceptions and your pod will crash.  Then with <code>restartPolicy: Always</code> Kubernetes will try to restart it; but if the database still isn't available, it will crash again; and you'll get to a CrashLoopBackOff state.  If the database does become available again then eventually Kubernetes will try to restart the Pod and it will succeed.</p>
<p>This same logic can apply at startup time.  If the Pod tries to start up, and the database isn't ready yet, and it crashes, Kubernetes will by default restart it, adding some delays after the first couple of attempts.  If the database starts up within 30 seconds or so then the application will be up within a minute or so.  The restart count will be greater than 0, but <code>kubectl logs --previous</code> will hopefully have a clear exception.</p>
<p>This will let you delete about half of what you show here.  Delete <em>all</em> of the <code>initContainers:</code> block; then, since you're not doing any Kubernetes API operations, delete the Role and RoleBinding objects too.</p>
<p>If you really do want to force the Pod to wait for the database and treat startup as a special case, I'd suggest a simpler shell script using the <code>mysql</code> client tool, or even the <code>wait-for</code> script that makes basic TCP calls (the mechanism described in <a href="https://stackoverflow.com/questions/31746182/docker-compose-wait-for-container-x-before-starting-y">Docker Compose wait for container X before starting Y</a>).  This still lets you avoid all of the Kubernetes RBAC setup.</p>
