How to Run SQL Server on a Mac

pfreitag

Pete Freitag

Posted on October 21, 2019

How to Run SQL Server on a Mac

You use a Mac, but you need to run Microsoft SQL Server. I never thought this would be so easy (I started using SQL Server 7 running Windows NT Server), but here's how I've been doing this for the past few years.

You need Docker

If you already have docker installed, then I have some great news for you: you can skip to the next step. If not, go and download it

Once you have it installed you should be able to run docker-compose -v from Terminal and it should output the version number.

Create a docker-compose.yml file

You don't have to use docker-compose but I find it makes the process easy, especially if you leave a project and come back to it 6 months later. Docker Compose lets you define one or more servers.

Here's a simple docker-compose.yml file.

version: '3'
services: sqlserver: 
  image: microsoft/mssql-server-linux:2017-latest 
  ports: 
    - "1401:1433" 
  volumes: 
    - ./db:/tmp/data 
  environment: 
    - ACCEPT\_EULA=Y 
    - "MSSQL\_SA\_PASSWORD=${DB\_PASS}" 
  command: - /tmp/data/run.sh

A few key points here. The ports section is mapping SQL Server port 1433 to my local port 1401. The password for the SA account will be set to the value of my DB_PASS environment variable, you may want to change how that works to suit your needs.

Now I have a sub folder called db with a few other files. The folder structure looks like this:

db/ 
  run.sh 
  import.sh 
  myDB.bak 
  mods.sql

Let's take a look at run.sh

#!/bin/sh

chmod a+x /tmp/data/import.sh

/tmp/data/import.sh & /opt/mssql/bin/sqlservr 

Here is import.sh

#!/bin/sh

#wait for sql server to start
sleep 10

#import database from bak file
/opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "$MSSQL\_SA\_PASSWORD" -Q "RESTORE DATABASE ExampleDb FROM DISK='/tmp/data/myDB.bak' WITH MOVE 'ExampleDb' TO '/var/opt/mssql/data/ExampleDb.mdf', MOVE 'ExampleDb\_log' TO '/var/opt/mssql/data/ExampleDb.ldf'"

#run mods.sql to modify the DB
/opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "$MSSQL\_SA\_PASSWORD" -d ExampleDb -i /tmp/data/mods.sql

Now Start SQL Server

Just run the following in terminal from the directory that has your docker-compose.yml file:

docker-compose up

At this point it should boot up SQLServer. It will be listening your localhost on port 1401, you can connect to it using SA and the password you set (eg DB_PASS environment variable).

Note that we could have done everything from the docker-compose.yml file if we wanted to, but I decided to break it up into scripts. This makes it easier to maintain a list of DB modifications or additions in the mods.sql file for example.

💖 💪 🙅 🚩
pfreitag
Pete Freitag

Posted on October 21, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How to Run SQL Server on a Mac
database How to Run SQL Server on a Mac

October 21, 2019