You have to mount the SQL file as a volumen from a configmap and use the psql cli to execute the commands from mounted file.

To execute commands from file you can change the command parameter on the yaml by this:

psql -a -f sqlCommand.sql

The configmap needs to be created using the file you pretend to mount more info here

kubectl create configmap sqlCommands.sql --from-file=sqlCommands.sql

Then you have to add the configmap and the mount statement on your job yaml and modify the command to use the mounted file.

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: [ "bin/sh", "-c", "psql -a -f /sqlCommand.sql" ]
        volumeMounts:
        - name: sqlCommand
          mountPath: /sqlCommand.sql
        env:
          - name: DB_HOST
            value: "knotted-iguana-postgresql"
          - name: DB_DATABASE
            value: "postgres"
      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
Answer from wolmi on Stack Overflow
🌐
GitHub
github.com › kubedb › docs › blob › master › docs › guides › postgres › initialization › script_source.md
docs/docs/guides/postgres/initialization/script_source.md at master · kubedb/docs
PostgreSQL supports initialization with .sh, .sql and .sql.gz files. In this tutorial, we will use data.sql script from postgres-init-scripts git repository to create a TABLE dashboard in data Schema. We will use a ConfigMap as script source.
Author   kubedb
🌐
Red Hat
developers.redhat.com › learning › learn:openshift:build-and-populate-database-using-kubernetes-init-containers › resource › resources:create-postgresql-instance-configmap-and-deployment-objects
Create the PostgreSQL instance, ConfigMap, and Deployment objects | Build and populate a database using Kubernetes init containers | Red Hat Developer
February 17, 2026 - Likewise, you can view the Kubernetes documentation related to configuring a pod to use a ConfigMap. When those two pieces of knowledge are combined, you get a deployment that, in our case, includes the following (an explanation follows this section of the YAML file): spec: initContainers: - name: init-createdb image: postgres:14 command: ["psql", "postgresql://postgres:postgres@postgresql", "-f", "/etc/rsalbums/create_database.sql"] volumeMounts: - name: albums-volume mountPath: /etc/rsalbums - name: init-builddb image: postgres:14 command: ["psql", "postgresql://postgres:postgres@postgresql/
Discussions

postgresql - Create or update existing postgres db container through kubernetes job - Stack Overflow
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 ... apiVersion: batch/v1 kind: Job metadata: name: init-db spec: template: metadata: name: init-db labels: app: init-postgresdb spec: containers: ... More on stackoverflow.com
🌐 stackoverflow.com
October 18, 2019
initdb scripts are not running in Postgres container
Name and Version bitnami/postgres 11.0.4 What steps will reproduce the bug? Install the postgres chart with the following values View DB or logs to see the script was not run Are you using any cust... More on github.com
🌐 github.com
15
February 16, 2022
postgresql - How to mount a sql file in a Init Container in order to bootstrap Postgres Database - Stack Overflow
I am working on adding an init-container in my app's deployment.yaml so I can decouple my postgres db bootstrap or schema evolution. As V1 I am trying to mount a sql file that will include the More on stackoverflow.com
🌐 stackoverflow.com
Postgres init script
For schema and data migrations, I wrote an init container that runs golang-migrate: https://github.com/golang-migrate/migrate More on reddit.com
🌐 r/docker
4
4
April 12, 2025
🌐
Coding With Spike!
codingwithspike.wordpress.com › 2019 › 12 › 09 › patterns-for-initializing-containers-in-kubernetes
Patterns for Initializing Containers in Kubernetes | Coding With Spike!
December 9, 2019 - This can be done by having an image in an initContainer that can execute kubectl or can query the Kubernetes API directly to check on the running state of processes. Lucky for you, I made a reusable tool for exactly this task. Please take a look at k8s-when-ready on GitHub and Dockerhub. When added to Kubernetes yaml, you could define something like this to wait for Postgres ...
🌐
GitHub
gist.github.com › onjin › 2dd3cc52ef79069de1faa2dfd456c945
example docker compose for postgresql with db init script · GitHub
I had the same issue but after a few hours of trying, I found a working combination of docker-compose and init script. Btw, I read here that the container shutting down and restarting is (apparently) part of the initialization process. This is part of my initdb.sh: #!/bin/bash psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" -d "$POSTGRES_DB" <<-EOSQL create schema if not exists $SCHEMA; create table $SCHEMA.todos ( id serial primary key, done boolean not null default false, task text not null, due timestamptz ); create role $ANON nologin; create role $AUTHENTICATOR noinherit login password '$POSTGRES_PASSWORD'; grant $ANON to $AUTHENTICATOR; EOSQL
🌐
GitHub
github.com › OpenG2P › postgres-init
GitHub - OpenG2P/postgres-init: Repository contain scripts to create Docker to initialize a Postgresql DB. · GitHub
The script is idempotent, meaning you can run it multiple times without causing errors if the database or user already exists. This project includes a Helm chart to deploy the database initializer as a Kubernetes Job. A Kubernetes cluster. ... Helm 3 installed. Customize the deployment by editing the postgres-initializer-chart/values.yaml file.
Author   OpenG2P
🌐
Belowthemalt
belowthemalt.com › 2022 › 09 › 18 › setup-of-spring-boot-application-initialization-of-postgresql-database-on-kubernetes-part-1
Setup of spring boot application & initialization of PostgreSQL database on Kubernetes - PART 1 - Blogs, Ideas, Train of Thoughts
September 19, 2022 - apiVersion: v1 kind: PersistentVolumeClaim metadata: name: postgresql-claim0 labels: app: postgresql tier: database spec: accessModes: - ReadWriteOnce resources: requests: storage: 100Mi · Next we want to build a configuration map object, which will have our database initialization scripts · Configuration maps are kubernetes objects which are used to store non-confidential data in key-value pairs
🌐
GitHub
gist.github.com › kofemann › eb0879de00ca1eccda88c01be44ddf27
Running postgres in kubernetes · GitHub
Clone this repository at &lt;script src=&quot;https://gist.github.com/kofemann/eb0879de00ca1eccda88c01be44ddf27.js&quot;&gt;&lt;/script&gt; Save kofemann/eb0879de00ca1eccda88c01be44ddf27 to your computer and use it in GitHub Desktop. Download ZIP · Running postgres in kubernetes ·
Find elsewhere
🌐
Stackgres
stackgres.io › doc › 1.1 › tutorial › using-initialdata › scripts
initialData Scripts :: StackGres Documentation
apiVersion: stackgres.io/v1 kind: SGCluster metadata: name: stackgres spec: initialData: scripts: - name: create-my-database script: | create database my_db owner postgres; and deploy to Kubernetes: kubectl apply -f sgcluster-with-raw-script.yaml · Note: Avoid this method to create sensitive data like user and passwords.
🌐
GitHub
github.com › bitnami › charts › issues › 9048
initdb scripts are not running in Postgres container · Issue #9048 · bitnami/charts
February 16, 2022 - 00_init_extensions.sh: | #!/bin/sh export PGPASSWORD=$POSTGRES_POSTGRES_PASSWORD psql -U postgres -d gis -c "create extension if not exists postgis; create extension if not exists hstore;" ... kind: PersistentVolumeClaim apiVersion: v1 metadata: name: postgres-seed-pvc spec: accessModes: - ReadWriteOnce resources: requests: storage: 2Gi storageClassName: gcp-ssd · The script is run and the postgis extension is enabled
Author   JesalR
🌐
Eksworkshop
developers.eksworkshop.com › introduction to kubernetes › initializing postgresql database with kubernetes configmaps
Initializing PostgreSQL Database with Kubernetes ConfigMaps | EKS Developers Workshop
Name: db-init-script Namespace: my-cool-app Labels: <none> Annotations: <none> Data ==== init.sh: ---- #!/bin/bash ... This lab guided you through the process of creating a Kubernetes ConfigMap that securely initializes your PostgreSQL database within a Minikube environment.
🌐
GitHub
gist.github.com › nathanborror › 36ebcb42472775b1aa4a8edc135ee615
Example Kubernetes setup with Postgres and two Services for serving an API and a static site using Ingress. Also have a CronJob example for kicks. · GitHub
April 12, 2022 - Clone this repository at &lt;script src=&quot;https://gist.github.com/nathanborror/36ebcb42472775b1aa4a8edc135ee615.js&quot;&gt;&lt;/script&gt; Save nathanborror/36ebcb42472775b1aa4a8edc135ee615 to your computer and use it in GitHub Desktop. ... Example Kubernetes setup with Postgres and two Services for serving an API and a static site using Ingress.
🌐
GitHub
github.com › helm › charts › issues › 9619
initdbScripts is set but doesn't run · Issue #9619 · helm/charts
November 28, 2018 - I install my chart: helm install --name postgres -f helm/tools/postgres/values.yaml stable/postgresql · What you expected to happen: The script will run when i install my chart for the first time · How to reproduce it (as minimally and precisely as possible): add the same configuration as I did · Anything else we need to know: I can see the script I added in /docker-entrypoint-initdb.d/ in running container, the db is up and running but databases and other stuff from my init script are not created.
🌐
GitHub
github.com › m99coder › postgres-on-kubernetes
GitHub - m99coder/postgres-on-kubernetes: PostgreSQL on Kubernetes · GitHub
$ # create stateful set with 3 replicas $ kubectl apply -f sfs.yaml $ # list stateful sets $ kubectl get statefulsets NAME READY AGE postgresql-sfs 3/3 16s $ # list pods $ kubectl get pods NAME READY STATUS RESTARTS AGE postgresql-sfs-0 1/1 Running 0 86s postgresql-sfs-1 1/1 Running 0 83s postgresql-sfs-2 1/1 Running 0 80s $ # inspect logs of a random pod $ kubectl logs postgresql-sfs-0 PostgreSQL Database directory appears to contain a database; Skipping initialization 2021-08-04 08:19:50.832 UTC [1] LOG: starting PostgreSQL 13.3 (Debian 13.3-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by g
Author   m99coder
🌐
Percona
percona.com › home › bootstrap postgresql on kubernetes
Bootstrap PostgreSQL on Kubernetes
September 24, 2025 - You can find all examples from this post in this GitHub repository. A single command to deploy the operator would be: Init SQL lets you create a database cluster with some initial data. Everything is created with the postgres admin user.
🌐
GitHub
github.com › kubedb › postgres-init-scripts
GitHub - kubedb/postgres-init-scripts
apiVersion: kubedb.com/v1alpha1 kind: Postgres metadata: name: pg spec: replicas: 1 version: 9.6.5 init: scriptSource: gitRepo: repository: "https://github.com/k8sdb/postgres-init-scripts.git" directory: "."
Starred by 4 users
Forked by 3 users
🌐
GitHub
github.com › orgs › supabase › discussions › 31147
Support for Kubernetes Postgres Operators (CNPG) · supabase · Discussion #31147
December 18, 2024 - The supabase-initdb-sql Secret's (create it as Secret not ConfigMap as CNPG always run Secrets before ConfigMap, maybe need to fix it) content can be created from https://github.com/supabase/postgres/tree/develop/migrations/db/init-scripts (but you have to exclude the migrations/10000000000000_demote-postgres.sql).
Top answer
1 of 2
1

You will have to do the following:

  1. Make the content of the SQL file as a ConfigMap like this, for example:

    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: mariadb-config
    data:
      mariadb-schema: "DROP DATABASE IF EXISTS test;\n\nCREATE DATABASE IF NOT EXISTS test;
    
  2. Make a volume from this config map in your deployment yaml like this:

     volumes:
     - name: mariadb-schema-config-vol
       configMap:
         name: mariadb-config
         defaultMode: 420
         items:
         - key: mariadb-schema
           path: mariadb-schema.sql
    

    And volume mount like this:

     volumeMounts:
     - mountPath: /var/db/config
       name: mariadb-schema-config-vol
    

Then your init container command will be like:

    ['sh', '-c', 'psql -a -f /var/db/config/mariadb-config.sql']

For your second question, make a shell script that reads the env variables (The db credentials - I am presuming that you are having them in secrets and using them as env variables) and then invoke this command:

   psql -a -f /var/db/config/mariadb-config.sql

So to make this happen the content of this script should be in a config map and execute the script from a volume mount, just like the above example.

Hope this helps.

2 of 2
0

Was looking into something similar and found the following approach as of 11.5.24 (postgres:16.2 docker image and kubernetes v1.31):

  1. I had an existing SQL init file init.sql.
  2. I ran kubectl create configmap initsql --from-file=init.sql to generate a configMap file. I renamed the file something like postgres-init.yaml.
  3. I kubectl apply -f postgres-init.yaml.
  4. I have a standard-fare postgres-deployment.yaml - basically copied from the official examples with a few modification.
  5. In volumes, I added:
    volumes:
      - ...
      - name: sql-init-mount
        configMap:
          name: initsql
          items:
           - key: init.sql
             path: init.sql
    
  6. In the same postgres-deployment.yaml I added to the postgres container itself:
    volumeMounts:
      - mountPath: /docker-entrypoint-initdb.d
        name: sql-init-mount
    
  7. The official postgres Docker image supports automatic initialization of any scripts dropped into docker-entrypoint-initdb.d.

I had a suspicion that using a configMap might accomplish the same thing without using containerInit or any commands. Turns out I was correct, you may need to wait moment but if you:

  1. minikube dashboard the deployed postgres pod can be found and you can easily exec in (if you're doing this locally) to verify the existing of the file (created corrected) and run: psql -U postgres -d postgres to login and query.
🌐
Reddit
reddit.com › r/docker › postgres init script
r/docker on Reddit: Postgres init script
April 12, 2025 -

I have a standard postgres container running, with the pg_data volume mapped to a directory on the host machine.

I want to be able to run an init script everytime I build or re-build the container, to run migrations and other such things. However, any script or '.sql' file placed in /docker-entrypoint-initdb.d/ only gets executed if the pg_data volume is empty.

What is the easiest solution to this – at the moment I could make a pg_dump pf the pg_data directory, then remove it’s content, and restore from the pg_dump, but it seems pointlessly convoluted and open to errors with potential data loss.

🌐
Opensource.com
opensource.com › article › 19 › 3 › how-run-postgresql-kubernetes
How to run PostgreSQL on Kubernetes | Opensource.com
The first step to using PostgreSQL with Kubernetes is installing an Operator. You can get up and running with the open source Crunchy PostgreSQL Operator on any Kubernetes-based environment with the help of Crunchy's quickstart script for Linux.