2

I'm following the instructions here on how to connect to MS SQL Server using docker.

After running the container you need to connect to do some setup:

docker exec -it sql1 "bash"
/opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P 'YourStrong!Passw0rd'

Create a database

CREATE DATABASE TestDB
GO

Then create a user

CREATE LOGIN TEST_USER WITH PASSWORD = 'YourStrong!Passw0rd'
GO
QUIT

Maybe you want to do a few other things like sp_addrolemember to be owner or other some such.

Is it possible to script these steps or combine it into single command?

e.g. run the docker command with the sqlcmd as a parameter and the required sql in a file as a parameter to that?

I don't want to compose my own container with these changes in.

2 Answers 2

1

For those ending up here who just want a "scriptable" solution, something like this should work (for mssql 2017):

#!/usr/bin/env bash
set -e

CONTAINER_NAME="replace-with-something-meaningfull"
SA_PASSWORD="YourStrong!Passw0rd"
DB_NAME="TestDB"

until docker exec -i ${CONTAINER_NAME} /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P ${SA_PASSWORD} -d master -Q "CREATE DATABASE ${DB_NAME}" 2>/dev/null
do
  sleep 2
done

until docker exec -i ${CONTAINER_NAME} /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P ${SA_PASSWORD} -d master -Q "CREATE LOGIN TEST_USER WITH PASSWORD = 'YourStrong!Passw0rd'" 2>/dev/null
do
  sleep 2
done

It is by no means perfect but should do the job.

Sign up to request clarification or add additional context in comments.

Comments

0

Basically you can create the desired behavior with custom Dockerfile. Take a look here https://github.com/mcmoe/mssqldocker

2 Comments

This is not an answer and should only be a comment as it only gives an idea and does not directly provide a solution. Also, the OP mentions what he does not want to do in his case
Additionally this docker image has container startup issues under its most recent version (from 2021)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.