<p>I have a Kubernetes cluster running the a PostgreSQL database, a Grafana dashboard, and a Python single-run application (built as a Docker image) that runs hourly inside a Kubernetes <code>CronJob</code> (see manifests below).  Additionally, this is all being deployed using ArgoCD with Istio side-car injection.</p>
<p>The issue I'm having (as the title indicates) is that my Python application cannot connect to the database in the cluster.  This is very strange to me since the dashboard, in fact, <em>can</em> connect to the database so I'm not sure what might be different for the Python app.</p>
<p>Following are my manifests (with a few things changed to remove identifiable information):</p>
<p>Contents of <code>database.yaml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: database
  name: database
spec:
  replicas: 1
  selector:
    matchLabels:
      app: database
  strategy: {}
  template:
    metadata:
      labels:
        app: database
    spec:
      containers:
      - image: postgres:12.5
        imagePullPolicy: &quot;&quot;
        name: database
        ports:
        - containerPort: 5432
        env:
          - name: POSTGRES_DB
            valueFrom:
              secretKeyRef:
                name: postgres-secret
                key: POSTGRES_DB
          - name: POSTGRES_USER
            valueFrom:
              secretKeyRef:
                name: postgres-secret
                key: POSTGRES_USER
          - name: POSTGRES_PASSWORD
            valueFrom:
              secretKeyRef:
                name: postgres-secret
                key: POSTGRES_PASSWORD
        resources: {}
        readinessProbe:
          initialDelaySeconds: 30
          tcpSocket:
            port: 5432
      restartPolicy: Always
      serviceAccountName: &quot;&quot;
      volumes: null
status: {}
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: database
  name: database
spec:
  ports:
  - name: &quot;5432&quot;
    port: 5432
    targetPort: 5432
  selector:
    app: database
status:
  loadBalancer: {}
</code></pre>
<p>Contents of <code>dashboard.yaml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: dashboard
  name: dashboard
spec:
  replicas: 1
  selector:
    matchLabels:
      app: dashboard
  strategy: {}
  template:
    metadata:
      labels:
        app: dashboard
    spec:
      containers:
      - image: grafana:7.3.3
        imagePullPolicy: &quot;&quot;
        name: dashboard
        ports:
          - containerPort: 3000
        resources: {}
        env:
          - name: POSTGRES_DB
            valueFrom:
              secretKeyRef:
                name: postgres-secret
                key: POSTGRES_DB
          - name: POSTGRES_USER
            valueFrom:
              secretKeyRef:
                name: postgres-secret
                key: POSTGRES_USER
          - name: POSTGRES_PASSWORD
            valueFrom:
              secretKeyRef:
                name: postgres-secret
                key: POSTGRES_PASSWORD
        volumeMounts:
          - name: grafana-datasource
            mountPath: /etc/grafana/provisioning/datasources
        readinessProbe:
          initialDelaySeconds: 30
          httpGet:
            path: /
            port: 3000
      restartPolicy: Always
      serviceAccountName: &quot;&quot;
      volumes:
        - name: grafana-datasource
          configMap:
            defaultMode: 420
            name: grafana-datasource
        - name: grafana-dashboard-provision
status: {}
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: dashboard
  name: dashboard
spec:
  ports:
  - name: &quot;3000&quot;
    port: 3000
    targetPort: 3000
  selector:
    app: dashboard
status:
  loadBalancer: {}
</code></pre>
<p>Contents of <code>cronjob.yaml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>---
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: python
spec:
  concurrencyPolicy: Replace
  # TODO: Go back to hourly when finished testing/troubleshooting
  # schedule: &quot;@hourly&quot;
  schedule: &quot;*/15 * * * *&quot;
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - image: python-tool:1.0.5
            imagePullPolicy: &quot;&quot;
            name: python
            args: []
            command:
              - /bin/sh
              - -c
              - &gt;-
                echo &quot;$(POSTGRES_USER)&quot; &gt; creds/db.creds;
                echo &quot;$(POSTGRES_PASSWORD)&quot; &gt;&gt; creds/db.creds;
                echo &quot;$(SERVICE1_TOKEN)&quot; &gt; creds/service1.creds;
                echo &quot;$(SERVICE2_TOKEN)&quot; &gt; creds/service2.creds;
                echo &quot;$(SERVICE3_TOKEN)&quot; &gt; creds/service3.creds;
                python3 -u main.py;
                echo &quot;Job finished with exit code $?&quot;;
            env:
              - name: POSTGRES_DB
                valueFrom:
                  secretKeyRef:
                    name: postgres-secret
                    key: POSTGRES_DB
              - name: POSTGRES_USER
                valueFrom:
                  secretKeyRef:
                    name: postgres-secret
                    key: POSTGRES_USER
              - name: POSTGRES_PASSWORD
                valueFrom:
                  secretKeyRef:
                    name: postgres-secret
                    key: POSTGRES_PASSWORD
              - name: SERVICE1_TOKEN
                valueFrom:
                  secretKeyRef:
                    name: api-tokens-secret
                    key: SERVICE1_TOKEN
              - name: SERVICE2_TOKEN
                valueFrom:
                  secretKeyRef:
                    name: api-tokens-secret
                    key: SERVICE2_TOKEN
              - name: SERVICE3_TOKEN
                valueFrom:
                  secretKeyRef:
                    name: api-tokens-secret
                    key: SERVICE3_TOKEN
          restartPolicy: OnFailure
          serviceAccountName: &quot;&quot;
status: {}
</code></pre>
<p>Now, as I mentioned Istio is also a part of this picture so I have a Virtual service for the dashboard since it should be accessible outside of the cluster, but that's it.</p>
<p>With all of that out of the way, here's what I've done to try and solve this, myself:</p>
<ol>
<li><p>Confirm the <code>CronJob</code> is using the correct connection settings (i.e. host, database name, username, and password) for connecting to the database.</p>
<p>For this, I added echo statements to the <code>CronJob</code> deployment showing the username and password (I know, I know) and they were the expected values.  I also know those were the correct connection settings for the database because I used them verbatim to connect the dashboard to the database, which gave a successful connection.</p>
<p>The data source settings for the Grafana dashboard:</p>
<p><a href="https://i.stack.imgur.com/KH2Rs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KH2Rs.png" alt="Connection settings used by Grafana data source" /></a></p>
<p>The error message from the Python application (shown in the ArgoCD logs for the container):</p>
<p><a href="https://i.stack.imgur.com/Co9Xu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Co9Xu.png" alt="Connection settings used by cron job" /></a></p>
</li>
<li><p>Thinking Istio might be causing this problem, I tried disabling Istio side-car injection for the <code>CronJob</code> resource (by adding this annotation to the <code>metadata.annotations</code> section: <code>sidecar.istio.io/inject: false</code>) but the annotation never actually showed up in the Argo logs and no change was observed when the <code>CronJob</code> was running.</p>
</li>
<li><p>I tried <code>kubectl exec</code>ing into the <code>CronJob</code> container that was running the Python script to debug more but was never actually able to since the container exited as soon as the connection error occurs.</p>
</li>
</ol>
<p>That said, I've been banging my head into a wall for long enough on this.  Could anyone spot what I might be missing and point me in the right direction, please?</p>

<p>I think the problem is that your pod tries to connect to the database before the istio sidecar is ready. And thus the connection can't be established.</p>
<p>Istio runs an init container that configures the pods route table so all traffic is routed through the sidecar. So if the sidecar isn't running and the other pod tries to connect to the db, no connection can be established.</p>
<p>There are two solutions.</p>
<p>First your job could wait for eg 30 seconds before calling <code>main.py</code> with some sleep command.</p>
<p>Alternatively you could enable <code>holdApplicationUntilProxyStarts</code>. By this main container will not start until the sidecar is running.</p>
