How to connect to Docker SQL Server in GitHub Actions

  .net-core, docker, github-actions, nuke-build, sql-server

I am trying to automate my testing using Nuke Build on GitHub. I am using a Docker to run a SQL Server container for testing. When it is run by GitHub Actions this error occurs. The image is successfully created and the error occurs when the tests try to access the database.

Error message:

Microsoft.Data.SqlClient.SqlException : Cannot open database "MyDB" requested by the login. The login failed.
Login failed for user ‘sa’

It runs successfully locally on my Windows 10 computer. I also tried to used Azure DevOps Pipeline and and the same error occurs. I tried looking around at similar issues such as this but they are not specific to when running on GitHub.

My .yaml script:

name: ci

on:
  push:
    branches:
      - main
      - feature/*
  pull_request:
    branches:
      - feature/*

jobs:
  ubuntu-latest:
    name: ubuntu-latest
    runs-on: ubuntu-latest
    steps:
      - uses: actions/[email protected]
      - name: Run './build.cmd Test'
        run: ./build.cmd Test

Snippets from my Build.cs modeled from this:

Target RunDbContainer => _ => _
    .Before(Compile)
    .Executes(() =>
    {
        DockerTasks.DockerRun(x => x
            .SetImage("mcr.microsoft.com/mssql/server:2019-latest")
            .SetEnv(new string[] { "ACCEPT_EULA=Y", "SA_PASSWORD=Password_01" })
            .SetPublish("1455:1433")
            .SetDetach(true)
            .SetName("sql1")
            .SetHostname("sql1"));
        System.Threading.Thread.Sleep(10000);
    });

Target Test => _ => _
        .Triggers(UnitTest, RunDbContainer, IntegrationTest, SqlServerContainerStop);

ConnectionString used by my tests to connection to the database. I tired using localhost and IP address gotten using:

"Server=127.17.0.2,1455;Database=MyDb;User Id=sa;Password=Password_01;MultipleActiveResultSets=True;Trusted_Connection=False;"

"Server=localhost,1455;Database=MyDb;User Id=sa;Password=Password_01;MultipleActiveResultSets=True;Trusted_Connection=False;"

I got the IP address following these instuctions:

docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' sql1

Source: Docker Questions

LEAVE A COMMENT