How to Run SQL Server on a Mac

September 27, 2019
databases

So you use a Mac, but you need to run Microsoft SQL Server. I never thought this would be so easy, but here's how I've been doing this for the past few years.

You need Docker

If you already have docker installed, 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 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 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.


Like this? Follow me ↯


You might also like:

1 person found this page useful, what do you think?

Post a Comment




  






Foundeo Inc.