======================== Correct Answer Start ========================

According to the Postgres image documentation you can extend the original image by running a script or an SQL file.

If you would like to do additional initialization in an image derived from this one, add one or more *.sql, *.sql.gz, or *.sh scripts under /docker-entrypoint-initdb.d (creating the directory if necessary). After the entrypoint calls initdb to create the default postgres user and database, it will run any *.sql files and source any *.sh scripts found in that directory to do further initialization before starting the service.

For your Dockerfile, you could do something like this.

FROM postgres:9.6.5

ENV POSTGRES_USER postgres
ENV POSTGRES_PASSWORD xxx
ENV POSTGRES_DB postgres

ADD create-role.sh /docker-entrypoint-initdb.d
ADD localDump.sql /docker-entrypoint-initdb.d

You will also need the create-role.sh script to execute the plsql command

#!/bin/bash
set -e

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
    CREATE ROLE read_only;
EOSQL

Note that I'm not a SQL DBA, the plsql command is just an example.

======================== Correct Answer End ========================

Original answer left for posterity :

Can you use psql ? Something like that.

FROM postgres:9.6.5

ENV POSTGRES_USER postgres
ENV POSTGRES_PASSWORD xxx
ENV POSTGRES_DB postgres

RUN psql -U postgres -d database_name -c "SQL_QUERY"

ADD localDump.sql /docker-entrypoint-initdb.d

You should find how to run SQL Query for Postgres from bash, and then add a RUN instruction in your Dockerfile.

Answer from Wassim Dhif on Stack Overflow
Top answer
1 of 1
6

======================== Correct Answer Start ========================

According to the Postgres image documentation you can extend the original image by running a script or an SQL file.

If you would like to do additional initialization in an image derived from this one, add one or more *.sql, *.sql.gz, or *.sh scripts under /docker-entrypoint-initdb.d (creating the directory if necessary). After the entrypoint calls initdb to create the default postgres user and database, it will run any *.sql files and source any *.sh scripts found in that directory to do further initialization before starting the service.

For your Dockerfile, you could do something like this.

FROM postgres:9.6.5

ENV POSTGRES_USER postgres
ENV POSTGRES_PASSWORD xxx
ENV POSTGRES_DB postgres

ADD create-role.sh /docker-entrypoint-initdb.d
ADD localDump.sql /docker-entrypoint-initdb.d

You will also need the create-role.sh script to execute the plsql command

#!/bin/bash
set -e

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
    CREATE ROLE read_only;
EOSQL

Note that I'm not a SQL DBA, the plsql command is just an example.

======================== Correct Answer End ========================

Original answer left for posterity :

Can you use psql ? Something like that.

FROM postgres:9.6.5

ENV POSTGRES_USER postgres
ENV POSTGRES_PASSWORD xxx
ENV POSTGRES_DB postgres

RUN psql -U postgres -d database_name -c "SQL_QUERY"

ADD localDump.sql /docker-entrypoint-initdb.d

You should find how to run SQL Query for Postgres from bash, and then add a RUN instruction in your Dockerfile.

Discussions

How to run sql script in sequence using docker compose
I’d like to run a script “amend_user.sql” after the users are created using the flyway job. Please advise. Many thanks, Sequence of steps: Download image & create postgres instance Run the flyway job Execute “amend_user.sql” in postgres database In the below docker-compose.yaml, this ... More on forums.docker.com
🌐 forums.docker.com
11
0
December 21, 2022
t sql - Run SQL script after start of SQL Server on docker - Stack Overflow
I wanted to do it dynamically, because I want to have SQL Server with concrete database immediately after ran container ... RUN gets used to build the layers in an image. CMD is the command that is run when you launch an instance (a "container") of the built image. Also, if your script depends on those environment variables, if it's an older version of Docker, it might fail because those variables are not defined the way you want them defined! In older versions of docker the Dockerfile ... More on stackoverflow.com
🌐 stackoverflow.com
psql - How do I run a sql file of inserts through docker run? - Stack Overflow
Given a file with a SQL insert: INSERT INTO countries (id, country_code, name) VALUES (1, 'AF', 'Afghanistan'), (2, 'AL', 'Albania'); I would like to run the file by using the docker run c... More on stackoverflow.com
🌐 stackoverflow.com
mysql - Docker, how to run .sql file in an image? - Stack Overflow
It's my first time working with Docker an I am not sure if I am doing things well. I have a rails applications that depends on a Mysql database, so I've configured the docker-compose.yml file like... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Docker Community
forums.docker.com › docker engine › compose
How to run sql script in sequence using docker compose - Compose - Docker Community Forums
December 21, 2022 - I’d like to run a script “amend_user.sql” after the users are created using the flyway job. Please advise. Many thanks, Sequence of steps: Download image & create postgres instance Run the flyway job Execute “amend_user.sql” in postgres database In the below docker-compose.yaml, this ...
🌐
Ankursheel
ankursheel.com › blog › run-sql-server-docker-container
How to run SQL Server in a Docker container - Ankur Sheel
Add the following lines to the docker file to initialize SQL Server. RUN mkdir -p /usr/work COPY ./build/*.sql /usr/work/ WORKDIR /usr/work RUN ( /opt/mssql/bin/sqlservr & ) \ | grep -q "Service Broker manager has started" \ && /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P $SA_PASSWORD -i create-db.sql \ && pkill sqlservr
🌐
Khalid Abuhakmeh
khalidabuhakmeh.com › running-sql-server-queries-in-docker
Running SQL Server Queries In Docker | Khalid Abuhakmeh
February 8, 2022 - We immediately connect to the sqlserver named container and start a bash session. ... You can also start Shell instead of bash. Your choice really. ... Both will get the job done. Now that we’re in the context of our container, we can run the tools bundled with the SQL Server image.
Top answer
1 of 3
14

RUN gets used to build the layers in an image. CMD is the command that is run when you launch an instance (a "container") of the built image.

Also, if your script depends on those environment variables, if it's an older version of Docker, it might fail because those variables are not defined the way you want them defined!

In older versions of docker the Dockerfile ENV command uses spaces instead of "="

Your Dockerfile should probably be:

FROM microsoft/mssql-server-windows-express
COPY ./create-db.sql .
ENV ACCEPT_EULA Y
ENV SA_PASSWORD ##$wo0RD!
RUN sqlcmd -i create-db.sql 

This will create an image containing the database with your password inside it.

(If the SQL file somehow uses the environment variables, this wouldn't make sense as you might as well update the SQL file before you copy it over.) If you want to be able to override the password between the docker build and docker run steps, by using docker run --env sa_password=##$wo0RD! ..., you will need to change the last line to:

CMD sqlcmd -i create-db.sql && .\start -sa_password $env:SA_PASSWORD \
-ACCEPT_EULA $env:ACCEPT_EULA -attach_dbs \"$env:attach_dbs\" -Verbose

Which is a modified version of the CMD line that is inherited from the upstream image.

2 of 3
9

You can follow this link https://github.com/microsoft/mssql-docker/issues/11. Credits to Robin Moffatt. Change your docker-compose.yml file to contain the following

mssql:
image: microsoft/mssql-server-windows-express
environment: 
  - SA_PASSWORD=##$wo0RD!
  - ACCEPT_EULA=Y
volumes:
  # directory with sql script on pc to /scripts/
  # - ./data/mssql:/scripts/
  - ./create-db.sql:/scripts/
command:
  - /bin/bash
  - -c 
  - |
    # Launch MSSQL and send to background
    /opt/mssql/bin/sqlservr &
    # Wait 30 seconds for it to be available
    # (lame, I know, but there's no nc available to start prodding network ports)
    sleep 30
    # Run every script in /scripts
    # TODO set a flag so that this is only done once on creation, 
    #      and not every time the container runs
    for foo in /scripts/*.sql
      do /opt/mssql-tools/bin/sqlcmd -U sa -P $$SA_PASSWORD -l 30 -e -i $$foo
    done
    # So that the container doesn't shut down, sleep this thread
    sleep infinity
Find elsewhere
Top answer
1 of 1
26

You can load the sql file during the build phase of the image. To do this you create a Dockerfile for the db service that will look something like this:

CopyFROM mysql:5.6
COPY setup.sh /mysql/setup.sh
COPY setup.sql /mysql/setup.sql
RUN /mysql/setup.sh

where setup.sh looks something like this:

Copy#!/bin/bash
set -e
service mysql start
mysql < /mysql/setup.sql
service mysql stop

And in your docker-compose.yml you'd change image to build: ./db or the path where you put your files.

Now this works if you have all your sql in a raw .sql file, but this wont be the case if you're using rails or a similar framework where the sql is actually stored in code. This leaves you with two options.

  1. Instead of using FROM mysql:5.6 you can use FROM your_app_image_that_has_the_code_in_it and apt-get install mysql .... This leaves you with a larger image that contains both mysql and your app, allowing you to run the ruby commands above. You'd replace the mysql < /mysql/setup/sql with the rails-app bundle exec rake db:create lines. You'd also have to provide an app config that hits a database on localhost:3306 instead of db:3306

  2. My preferred option is to create a script which exports the sql into a .sql file, which you can then use to build your database container. This is a bit more work, but is a lot nicer. It means that instead of running rails-app bundle exec rake db:create you'd just run the script to load a db.

Such a script would look something like this:

Copy#!/bin/bash
set -e
docker-compose build rails-app
docker run -d --name mysql_empty mysql:5.6
docker run --link mysql_empty:db -v $PWD:/output project_rails-app export.sh

where export.sh looks something like this:

Copy#!/bin/bash
set -e
RAILS_ENV=development
rails-app bundle exec rake db:create
mysqldump > /output/setup.sql

You could also replace the docker run script with a second compose file if you wanted to.

🌐
DEV Community
dev.to › n350071 › login-to-mysql-on-docker-and-run-a-sql-file-2bk7
🐳 Login to MySQL on Docker and run a SQL file - DEV Community
October 29, 2019 - You maintain an app with MySQL and develop it on Docker. You have a dump file as .sql. Then, you want to run it.
🌐
Daniel Genezini
blog.genezini.com › p › how-to-run-scripts-on-sql-server-container-startup
How to run scripts on SQL Server container startup
May 15, 2023 - /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $MSSQL_SA_PASSWORD -d master -i setup.sql echo "Configuration completed." This is the script that will be run. Here I’m just creating the database. ... Now, we have to build the container image from the Dockerfile we created.
🌐
Microsoft Learn
learn.microsoft.com › en-us › sql › linux › quickstart-install-connect-docker
Docker: Run Containers for SQL Server on Linux - SQL Server | Microsoft Learn
This quickstart shows how to use Docker to run the SQL Server Linux container images. You connect to a database and run a query.
🌐
CopyProgramming
copyprogramming.com › howto › shell-how-to-run-sql-in-dockerfile-mysql
How to Run SQL in Dockerfile MySQL: Latest Features, Best Practices & Complete Guide 2026
January 1, 2026 - The official MySQL Docker image provides an automated initialization mechanism through the /docker-entrypoint-initdb.d directory. This is the most reliable and widely-adopted approach for running SQL scripts during container first-time startup.
🌐
LogRocket
blog.logrocket.com › home › how to run sql server in a docker container
How to run SQL Server in a Docker container - LogRocket Blog
June 4, 2024 - Now that we have our setup script, we can run it against our database container using mssql: $ mssql -u sa -p change_this_password mssql> .run my_db_setup.sql USE master; OK Executed in 0 ms CREATE DATABASE SampleDB; OK Executed in 0 ms CREATE TABLE dbo.MyTable ( id bigint IDENTITY(1,1) PRIMARY KEY, name varchar(500) null ) OK Executed in 0 ms
🌐
Iditect
iditect.com › program-example › mysql--executing-sql-scripts-on-docker-container.html
mysql - Executing SQL scripts on docker container
"MySQL run SQL script initialization Docker" Code Implementation (Dockerfile): FROM mysql ENV MYSQL_ROOT_PASSWORD your_password ENV MYSQL_DATABASE your_database ENV MYSQL_USER your_user ENV MYSQL_PASSWORD your_password COPY your_script.sql /docker-entrypoint-initdb.d/ Description: Creating a custom Docker image with MySQL initialization using a SQL script.
🌐
Medium
medium.com › @aedemirsen › execute-sql-commands-at-postgresql-db-startup-with-docker-2be0abadec48
Execute Sql Commands At Postgresql DB Startup With Docker | by Ahmet Emre DEMİRŞEN | Medium
January 17, 2026 - version: "3.8" services: postgresql: image: postgres container_name: postgres_db restart: always environment: POSTGRES_DB: ${POSTGRES_DB} POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_ROOT_PASSWORD: ${POSTGRES_ROOT_PASSWORD} ports: - ${POSTGRES_PORT}:5432 volumes: - ./postgres/data:/var/lib/postgresql/data - ./postgres/init.sql:/docker-entrypoint-initdb.d/init.sql
🌐
Medium
bricefotzo.medium.com › how-to-quickly-run-sql-queries-using-docker-3f310eaf6d3e
How to quickly run SQL queries using Docker?
June 6, 2024 - :/query.sql: This specifies the destination path inside the container. After the command is executed, your SQL script will be accessible inside the container at the path /query.sql. Run your SQL script within the containerized database to see the results.