Running mssql on docker

Here is a quick walk through to setup a simple MSSQL instance on docker and initialize the instance with a data.

First we will setup a few scripts to startup sql, create a database and initialize it with data.

entrypoint.sh

#start SQL Server, start the script to create/setup the DB
 /init.sh & /opt/mssql/bin/sqlservr

init.sh — Be sure to save this file with LF endings if on Windows or you will throw errors at runtime.

# A better solution would be to check server status, but
# sleep will do
sleep 15s

/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P VeRYSECR3T! -d master -i dockersql.sql

dockersql.sql

 IF(DB_ID(N'dockersql') IS NULL)
 CREATE DATABASE dockersql

 GO

 USE dockersql
 GO

IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='Places'
 and xtype='U')
BEGIN
 CREATE TABLE dbo.Places (
     Id INT IDENTITY(1,1) NOT NULL,
     Name varchar(25) NOT NULL
 );

INSERT INTO dbo.Places (Name)
VALUES
('Dallas'),('Austin'),('Houston')
END

Next we will create the Dockerfile that will copy the scripts into the image and set our custom entry point. As you can see from above, entrypoint.sh will call init.sh. init.sh will sleep to give time for sql to come up. Then it will call dockersql.sql to create and populate a simple database.

Dockerfile

# Using image for Sql Server 2019
FROM mcr.microsoft.com/mssql/server:2019-GA-ubuntu-16.04
  
COPY . /
CMD /bin/bash ./entrypoint.sh

Let’s test it out by building and then running the instance.

docker build . -t dockersql
docker run -it -p 1433:1433 --env ACCEPT_EULA=Y --env MSSQL_SA_PASSWORD=VeRYSECR3T! -v sqlvolume1:/var/opt/mssql dockersql

Notice the volume param, this will create a volume that will persist even after stopping the container.

You show now be able to connect to this instance and query the Places table.


https://github.com/runwithliz/DockerSQLBlog1

Leave a comment