opticyclic
opticyclic

Reputation: 8136

How Do I Create A Database And User In Docker Using A Script?

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.

Upvotes: 2

Views: 11876

Answers (2)

ndx
ndx

Reputation: 115

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.

Upvotes: 1

ktsirkou
ktsirkou

Reputation: 9

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

Upvotes: 0

Related Questions