Hosting .NET Application with DB on Docker

Create DB and run App

First off we'll create a network in docker to get some isolation for our app and db

docker network create contosouniversity

To check the list of available networks run

docker network ls

Run SQL server using the official image. If this step fails check the end notes to debug

docker run -d \
    --network contosouniversity \
    -e 'ACCEPT_EULA=Y' \
    -e 'SA_PASSWORD=uniPassword.1' \
    --name 'contosouniversityserver' \
    -p 1433:1433 \

Create a database

docker exec sqltestdb /opt/mssql-tools/bin/sqlcmd \
    -S localhost -U SA -P 'uniPassword.1' \
    -Q "CREATE DATABASE universitydb"

Run the application on the same network as the database

docker run -d --network contosouniversity \
    -p 8080:80 \
    --name contosouniversity \
    -e "SQL_PASSWORD=uniPassword.1" \
    -e "SQL_SERVER=contosouniversityserver" \
    -e "SQL_USER=sa" \
    -e "SQL_DBNAME=unidb" \
    -e "ASPNETCORE_ENVIRONMENT=Production" \

Debugging tips

  • As an alternative approach for creating a db or to test that db creation worked
docker exec -it contosouniversityserver "bash"
/opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "uniPassword.1"
SELECT Name from sys.Databases
NOTE: You must type GO on a new line to execute the previous commands
  • To check the environment variables on a container run this
docker inspect -f '{{range $index, $value := .Config.Env}}{{$value}} {{end}}' [container ID]

  • Sometimes port 1433 used by MS SQL will be reserved by Hyper-V and the container will fail to run to check if this is the case run the below steps.
    netsh int ipv4 show excludedportrange protocol=tcp

The ports listed are managed by hyper-v and the only way to remove the port 1433 here is to disable hyper-v, reserve the port 1433 so hyper-v doesn't reserve it back. Disable hyper-v

dism.exe /Online /Disable-Feature:Microsoft-Hyper-V

Reserve the port 1433

netsh int ipv4 add excludedportrange protocol=tcp startport=1433 numberofports=1

Re Enable hyper-v

dism.exe /Online /Enable-Feature:Microsoft-Hyper-V /All

Start docker and run the container again