Skip to content

Instantly share code, notes, and snippets.

@shawmanz32na
Last active July 11, 2023 17:18
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save shawmanz32na/ee39c8aecdf643384e810d8dd4c8afae to your computer and use it in GitHub Desktop.
mssql-docker with seed data

mssql-docker image with seed data

This extends the Microsoft/mssql-docker image with application seed data.

Once these files are copied into a directory, place the application's .bak file in that directory and build the image.

To run the extended image, use docker run -e ACCEPT_EULA=Y -e SA_PASSWORD=yourStrong(!)Password -p 1433:1433 mssql-docker-extended

THIS IS NOT A PRODUCTION_READY SOLUTION

This approach requires a wait (guaranteed to be the wrong amount of time), for mssql to start, both when building the image (see docker-entrypoint.sh) and when starting any images that use this image. I'd much prefer Microsoft provide a way to test if/when MSSQL is running to be able to remove the waits, and provide a "real" way to extend the image with seed data (see microsoft/mssql-docker#229).

#!/bin/bash
set -e
if [ "$1" = '/opt/mssql/bin/sqlservr' ]; then
# If this is the container's first run, initialize the application database
if [ ! -f /tmp/app-initialized ]; then
# Initialize the application database asynchronously in a background process. This allows a) the SQL Server process to be the main process in the container, which allows graceful shutdown and other goodies, and b) us to only start the SQL Server process once, as opposed to starting, stopping, then starting it again.
function initialize_app_database() {
# Wait a bit for SQL Server to start. SQL Server's process doesn't provide a clever way to check if it's up or not, and it needs to be up before we can import the application database
sleep 15s
# Restore the application database
/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P "$SA_PASSWORD" -Q "RESTORE DATABASE app FROM DISK = '/usr/src/app/app.bak' WITH MOVE 'App_Data' TO '/var/opt/mssql/data/app.mdf', MOVE 'App_Log' TO '/var/opt/mssql/data/app.ldf';"
# Create the application user
/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P "$SA_PASSWORD" -i /usr/src/app/create-app-user.sql
# Note that the container has been initialized so future starts won't wipe changes to the data
touch /tmp/app-initialized
}
initialize_app_database &
fi
fi
exec "$@"
FROM microsoft/mssql-server-linux
COPY . /usr/src/app
ENTRYPOINT [ "/bin/bash", "/usr/src/app/docker-entrypoint.sh" ]
CMD [ "/opt/mssql/bin/sqlservr" ]
@murhsynergy
Copy link

Could you use https://github.com/vishnubob/wait-for-it in place of sleep?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment