I am running SQL Server Express 2014 under a Docker for Windows container using the following command:
docker run -it -p 1433:1433 -v C:/Databases/:C:/Databases/ --env sa_password=P@ssW0rd --env attach_dbs="[{'dbName':'trunk','dbFiles':['C:\\Databases\\trunk_Log.mdf','C:\\Databases\\trunk.ldf']}]" --name sql microsoft/mssql-server-2014-express-windows
The database successfully starts up, and I can connect to it with SQL Server Management Studio. The name of the server seems to be {First 12 Characters of the Docker Container ID}\SQLEXPRESS
Since the container id changes every time a container is started, having a statically-defined connection string is impossible. It seems you need to use the Docker REST API to get the name of the container, and then use it in your connection string.
public string GetSqlServerDockerContainer(string name)
{
// tcp://localhost:2375 is the address that exposed the REST endpoints
DockerClient client = new DockerClientConfiguration(new Uri("tcp://localhost:2375")).CreateClient();
var containers = client.Containers.ListContainersAsync(new ContainersListParameters() { Limit = 10 }).Result;
foreach (var container in containers)
{
if (container.Names != null && container.Names[0].Equals(name, StringComparison.OrdinalIgnoreCase))
return container.ID;
if (container.Image != null && container.Image.IndexOf("mssql", StringComparison.OrdinalIgnoreCase) >= 0)
return container.ID;
}
return null;
}
var containerId = app.GetSqlServerDockerContainer("/sql");
containerId = containerId.Substring(0, 12); // the "server" name that SQL Server uses is the first 12 characters of the container id
string connectionString = $"Data Source={containerId}\\SQLEXPRESS;Initial Catalog=trunk;Uid=sa;Pwd=P@ssW0rd";
It doesn’t seem that you can connect to the database using {Container Name}\SQLEXPRESS. You need the container ID.
I have a two part question:
- Is there any better way to resolve the connection string to a running database?
- In my C# app which is running outside of the container, I am creating a SqlConnection and then calling connection.Open(). It seems to take a few seconds to actually connect to the database. Is there any way to get around the slowness in connecting?
Thanks,
Marc