I have some C# integration tests that spin up a MySql docker container, build a schema, interact with it and then tear down the container. It works fine when I run dotnet test but fails with Cannot assign requested address /var/run/docker.sock when I try to run it as part of a docker build command.

TestContainer setup:

        var testcontainerBuilder = new TestcontainersBuilder<MySqlTestcontainer>()
            .WithDatabase(new MySqlTestcontainerConfiguration()
            {
                Database = MYSQL_DBNAME,
                Username = MYSQL_USER,
                Password = password,
                Port = MYSQL_PORT
            })
            .WithEnvironment("MYSQL_ROOT_HOST", "%")
            .WithOutputConsumer(_outputConsumer)
            .WithCleanUp(true);
        _container = testcontainerBuilder.Build();
        await _container.StartAsync();

Things I've checked:

  • port is available
  • _container.ConnectionString is localhost. I suspect this is related.

My suspicion is that the docker build environment can't see the MySql container at localhost.

1

There are 1 answers

0
Mike Parkhill On BEST ANSWER

The solution I came up with was to break the docker build into two steps. One for the tests and one for packaging the build. I then run the built test container with a file mount on /var/run/docker.sock

Dockerfile.test:

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS test
WORKDIR /src/
RUN PATH="$PATH:/root/.dotnet/tools" dotnet tool install -g dotnet-format --version 4.0.130203
COPY . /src/
RUN dotnet restore && \
    PATH="$PATH:/root/.dotnet/tools" dotnet format --check --verbosity diagnostic

ENTRYPOINT ["dotnet", "test", "--logger:trx"]

Commands:

docker build --build-arg -t test:1 -f ./Dockerfile.test  .
docker run -v /var/run/docker.sock:/var/run/docker.sock test:1

Inspired by this post: What is the result of mounting `/var/run/docker.sock` in a Docker in Docker scenario?