How to connect to Docker SQL Server in GitHub Actions

986 Views Asked by At

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/checkout@v1
      - 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);

The database is created and deleted during testing using EF Core. A connection string is used to create a DbContext. Then context.Database.EnsureCreated() is used to create the database.

For the connection string I tired using localhost and the 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
0

There are 0 best solutions below