<p>I have a Postgres DB container which is running in a Kubernetes cluster. I need to write a Kubernetes job to connect to the Postgres DB container and run the scripts from SQL file. I need to understand two things here</p>

<ol>
<li>commands to run SQL script </li>
<li>how to load SQL file in Job.yaml file </li>
</ol>

<p>Here is my sample yaml file for Kubernetes job</p>

<pre><code>apiVersion: batch/v1
kind: Job
metadata:
  name: init-db
spec:
  template:
    metadata:
      name:  init-db
      labels:
        app: init-postgresdb
    spec:
      containers:
      - image: "docker.io/bitnami/postgresql:11.5.0-debian-9-r60"
        name: init-db
        command:
        - psql -U postgres 
        env:
          - name: DB_HOST
            value: "knotted-iguana-postgresql"
          - name: DB_DATABASE
            value: "postgres"
      restartPolicy: OnFailure  
</code></pre>

Pandit Biradar
<p>You have to mount the SQL file as a volumen from a configmap and use the <code>psql</code> cli to execute the commands from mounted file.</p>
<p>To execute commands from file you can change the command parameter on the yaml by this:</p>
<pre><code>psql -a -f sqlCommand.sql
</code></pre>
<p>The configmap needs to be created using the file you pretend to mount more info <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/" rel="nofollow noreferrer">here</a></p>
<pre><code>kubectl create configmap sqlCommands.sql --from-file=sqlCommands.sql
</code></pre>
<p>Then you have to add the configmap and the mount statement on your job yaml and modify the command to use the mounted file.</p>
<pre><code>apiVersion: batch/v1
kind: Job
metadata:
  name: init-db
spec:
  template:
    metadata:
      name:  init-db
      labels:
        app: init-postgresdb
    spec:
      containers:
      - image: &quot;docker.io/bitnami/postgresql:11.5.0-debian-9-r60&quot;
        name: init-db
        command: [ &quot;bin/sh&quot;, &quot;-c&quot;, &quot;psql -a -f /sqlCommand.sql&quot; ]
        volumeMounts:
        - name: sqlCommand
          mountPath: /sqlCommand.sql
        env:
          - name: DB_HOST
            value: &quot;knotted-iguana-postgresql&quot;
          - name: DB_DATABASE
            value: &quot;postgres&quot;
      volumes:
        - name: sqlCommand
          configMap:
          # Provide the name of the ConfigMap containing the files you want
          # to add to the container
          name: sqlCommand.sql
      restartPolicy: OnFailure
</code></pre>
