Skip to content

Instantly share code, notes, and snippets.

@sdcondon
Last active December 22, 2020 13:03
Show Gist options
  • Save sdcondon/02ac17073e68409f40179f940ac6be77 to your computer and use it in GitHub Desktop.
Save sdcondon/02ac17073e68409f40179f940ac6be77 to your computer and use it in GitHub Desktop.
Dockerfile for a SQL server instance built to include a database defined in a given SQL script
# A couple of references:
# - https://github.com/twright-msft/mssql-node-docker-demo-app (sql setup, but at run-time)
# - https://www.wintellect.com/devops-sql-server-dacpac-docker/ (build-time setup, but of DACPAC)
FROM mcr.microsoft.com/mssql/server:2017-latest AS final
# Copy schema.sql from wherever into a tmp directory in the image
# This file is assumed to include all your DB objects as CREATE statements
COPY /TestDatabase/schema.sql /tmp/schema.sql
# Install dos2unix and run it to ensure correct line endings in schema file
RUN apt-get -y update \
&& apt-get install -y dos2unix \
&& dos2unix /tmp/schema.sql
# Configure external build arguments to allow configurability
ARG DBNAME
ARG SAPASSWORD
# Since we need to connect to the server during the build, we need to define
# the sa password environment variable at build time - hence the build arg, above
ENV SA_PASSWORD=$SAPASSWORD
# Using bash, launch SQL Server (accepting the EULA for the purposes of the build),
# create the database (retrying as needed until the server is responding positively),
# run the schema script, delete the schema script, and finally stop the server.
# NB: It seems the EULA only needs to be accepted once - after that the server will start
# regardless. Which seems a little wrong to me, but the upshot of this is that the when
# running this image, you don't need to set the ACCEPT_EULA environment variable
SHELL ["/bin/bash","-c"]
RUN ( /opt/mssql/bin/sqlservr --accept-eula & ) \
&& for i in {1..30}; do \
/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $SA_PASSWORD -d master -Q "CREATE DATABASE $DBNAME;"; \
if [ $? -eq 0 ]; then \
echo "Server responding and database $DBNAME created"; \
break; \
else \
echo "Server not yet responding positively..."; \
sleep 1; \
fi; \
done \
&& /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $SA_PASSWORD -d $DBNAME -i /tmp/schema.sql \
&& rm /tmp/schema.sql \
&& pkill sqlservr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment