WSL2上のDockerでSQL Server実行してSSMSで繋ぐまで

SQL Serverの動作確認のためにWSL2のDocker上でSQL Server起動して、SQL Server Management Studio (SSMS)で接続するところまでです。

前提

  • WSL2とDockerが入っていること
  • SSMSがインストールされていること(ここからダウンロード)

SQL Server起動

SAのパスワードを変数に設定しておきます。

$ PASSWORD=someYourP@ssw0rd

こちらのイメージを利用します。

https://hub.docker.com/_/microsoft-mssql-server

実行は簡単で、以下のコマンドを実行するだけです。

docker run --name mssql  -d -p 1433:1433 \
 -e "ACCEPT_EULA=Y" \
 -e "SA_PASSWORD=${PASSWORD}" \
 -e "MSSQL_PID=Standard" \
 mcr.microsoft.com/mssql/server:2019-GA-ubuntu-16.04

-p 1433:1433 の部分はListenするポートを設定します。例えば、 -p 14331:1433 とすると14331ポートで接続できます。複数インスタンス使いたいときなど利用します。

MSSQL_PID はエディションの指定になります。

以下のように指定可能です。

MSSQL_PID is the Product ID (PID) or Edition that the container will run with. Acceptable values:
Developer : This will run the container using the Developer Edition (this is the default if no MSSQL_PID environment variable is supplied)
Express : This will run the container using the Express Edition
Standard : This will run the container using the Standard Edition
Enterprise : This will run the container using the Enterprise Edition
EnterpriseCore : This will run the container using the Enterprise Edition Core : This will run the container with the edition that is associated with the PID

sqlcmdで接続

上記で起動したイメージ内にsqlcmdが入っているので、そちらで接続できます。

docker exec -it mssql /opt/mssql-tools/bin/sqlcmd \
    -S localhost -U SA -P ${PASSWORD}

SSMSから接続

実はここで少し詰まったのですが、2020/03/10時点ではlocalhostでは接続できないようでした。WSL2ではLinux側も自身のTCPスタックを持っているので、WSL2で立ち上げているLinuxのIPに直接接続しにいくことで接続できました。

以下のようにWSL2のeth0のIP調べます。

$ ip a | grep eth0 | grep inet
    inet 172.23.110.151/20 brd 172.23.111.255 scope global eth0

tcp:172.23.110.151,1433 のように設定します。( tcp: は無くてもOK)

接続できました。

参考URL

docs.microsoft.com

www.atmarkit.co.jp