- 1 year ago
Docker with Windows auth to SQL Server
To connect a Docker container to a SQL Server database using Windows authentication, you need to perform a few configuration steps. Here's a general outline of the process:
Create a Docker network: First, create a Docker network that allows the container and the SQL Server instance to communicate with each other. You can create a network using the following command:
shelldocker network create sql-net
Run the SQL Server container: Start a new SQL Server container with the necessary environment variables and network configuration. You need to provide the SA password, the SQL Server instance name, and the Docker network. Use a command like this:
shelldocker run -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=YourPassword123' -p 1433:1433 --network sql-net --name sql-server -d mcr.microsoft.com/mssql/server
Replace
'YourPassword123'
with your desired SA password. This command starts a SQL Server container and maps the host's port 1433 to the container's port 1433.Install the SQL Server client tools (optional): If you need to connect to the SQL Server from within another Docker container, you might want to install the SQL Server client tools. This step is not necessary if you're connecting from the host machine or using a different tool like SQL Server Management Studio (SSMS) outside the container.
Connect to SQL Server: Now that the SQL Server container is running, you can connect to it using Windows authentication. Here's a sample connection string in Python using the
pyodbc
library:pythonimport pyodbc
conn_str = (
'Driver={ODBC Driver 17 for SQL Server};'
'Server=sql-server;'
'Database=YourDatabase;'
'Trusted_Connection=yes;'
)
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
cursor.execute("SELECT @@VERSION")
row = cursor.fetchone()
print(row[0])
cursor.close()
conn.close()
In the connection string, replace
'sql-server'
with the name or IP address of the SQL Server container. Make sure the container is accessible from your host or within the Docker network.Note: The
ODBC Driver 17 for SQL Server
is used in this example, but you may need to install a different driver depending on your programming language and environment.
That's it! With these steps, you should be able to connect a Docker container to a SQL Server database using Windows authentication. Make sure you have the necessary permissions and firewall settings configured on the SQL Server side to allow connections.