I wish there were a utility this simple for it. Unfortunately there is an extra step to make (at least for SQL Server)
Your compose needs to add an entry point file, this is what we use.
my_db_container:
image: mcr.microsoft.com/mssql/server:2022-latest
environment:
ACCEPT_EULA: "Y"
MSSQL_SA_PASSWORD: "Hey!Don't look here. Bad!"
ports:
- "1433:1433"
networks:
- dev_network
volumes:
- ./db-init/init.sql:/db/init.sql
- ./db-init/entrypoint.sh:/entrypoint.sh
entrypoint: ["/bin/bash", "/entrypoint.sh"]
First our docker-compose sets up the db image. The networks: - dev_network is to make it easier to reach my db container from my app container. The 'volumes' are how my container has access to the scripts it needs to create the db. In my docker-compose project I also need to have the two files specified in 'volumes' (under db-init)
init.sql - just needs to be a bit more involved. Here is my script where some_name = Jeff
IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = N'Jeff')
BEGIN
CREATE DATABASE [Jeff];
END
entrypoint.sh. This is the one that I had to fight with as mssql_tools can have different names depending on your image. If it fails just verify /opt/mssql-tools18/bin/sqlcmd is where you expect by looking at the file system through docker desktop. In the below case, we set the entry point to wait until sql is live, then run our init script.
#!/bin/bash
# Start SQL Server in the background
/opt/mssql/bin/sqlservr &
# Wait until SQL Server is ready
echo "Waiting for SQL Server to be available..."
until /opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P "$MSSQL_SA_PASSWORD" -C -Q "SELECT 1" > /dev/null 2>&1; do
sleep 1
echo "Still Waiting for SQL Server to be available..."
done
# Run your init script
echo "Running init.sql..."
/opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P "$MSSQL_SA_PASSWORD" -C -i /db/init.sql
echo "Finished running init.sql."
# Keep container alive
wait
CREATE DATABASE IF NOT EXISTSis not valid tsql syntax. You can use this instead:IF NOT EXISTS (SELECT 1 FROM sys.databases WHERE name='some_name') CREATE DATABASE some_name;docker-entrypoint-initdb.d/init-script.sqlisn't supported by SQL Server - I think it's a Postgres-only feature