How to connect to a local SQL Server Express database from a Docker-Composed C# application?
Asked Answered
C

2

5

Original (which works fine) docker file which connects to a SQL Server database in Azure looks like this:

version: '3.4'

services:
  my.service:
    build:
        dockerfile: Test/Test/Dockerfile
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - MyDatabase__ConnectionString=Server=tcp:xxx.windows.net,1433;Initial Catalog=my-catalog;User ID=SA@dbs;Password='xxx';Persist Security Info=False;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30

What should the "MyDatabase__ConnectionString" be if I want to connect to my local SQL Server Express?

I tried these options, but none work?

  • tcp:host.docker.internal\\SQLEXPRESS,1433;***
  • tcp:host.docker.internal\\SQLEXPRESS;***
  • tcp:localhost\\SQLEXPRESS,1433;***
  • host.docker.internal\\SQLEXPRESS,1433;***
  • host.docker.internal\\SQLEXPRESS;***
  • localhost\\SQLEXPRESS;***

Also note that TCP is enabled for my local SQL Server Express:

TCP is enabled

Cerous answered 15/2, 2021 at 14:59 Comment(1)
Leave off \SQLEXPRESS?Adrenocorticotropic
C
7

By following this blog-post I could get it working.

See the steps below:

1] Make sure that TCP is enabled, and 'Listen All is set to Yes' for this SQLExpress instance: enter image description here

2] Define a (free) fixed custom port on which the SQLExpress instance should listen on (e.g. 49172) enter image description here

3] Make sure that the Firewall on Windows allows local connections to this port: enter image description here

4] Now change the connection-string to this.

Server=host.docker.internal,49172;Initial Catalog=Initial Catalog=my-catalog;***

In this example the host.docker.internal is used, which automatically resolves this the Docker internal (nat) ip-address. In my case this was this: enter image description here

(However you don't need to use this ip-address if you just use host.docker.internal)

Cerous answered 16/2, 2021 at 7:42 Comment(0)
C
3

I tried the same things but didn't manage to make it work. Instead I run sqlserver in docker too. Then you can:

  • Connect to sqlserver from another docker container: Server=host.docker.internal,1434;Database=UsersDb;User ID=sa;Password=P@ssw0rd12345!!
  • Connect from the host machine Server=127.0.0.1,1434;Database=UsersDb;User ID=sa;Password=P@ssw0rd12345!!
Cassino answered 16/2, 2021 at 7:24 Comment(1)
For reference, use the following commands to get your Dockerized SQL Server up and running: docker pull mcr.microsoft.com/mssql/server:2022-latest docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=superSecurePassword" -p 1434:1433 --name myprojectdb -h mssqlserver -d mcr.microsoft.com/mssql/server:2022-latestLanguishing

© 2022 - 2024 — McMap. All rights reserved.