I need help to run a simple Python script in Docker to query a SQL Server database. The SQL Server instance is not Dockerised, it's just running on a VM. The Python script succeeds when run from my laptop, but not when run via Docker.
Based on chat with a colleague I suspect it is to do with my work's networking (ports, DirectAccess, ip addresses, DNS etc) but I don't have enough foundational knowledge to know how to test/fix this. I've spent hours, but not been able to get this working.
pyodbc kept giving me 'timeout' errors
pymssql gives me the following:
pymssql._mssql.MSSQLDatabaseException: (20009, b'DB-Lib error message 20009, severity 9:\nUnable to connect: Adaptive Server is unavailable or does not exist ([email protected])\nNet-Lib error during Connection refused (111)\nDB-Lib error message 20009, severity 9:\nUnable to connect: Adaptive Server is unavailable or does not exist ([email protected])\nNet-Lib error during Connection refused (111)\n')
Can someone help me fix the Docker - SQLServer connectivity issues?
I am in no way wedded to pymssql. At this stage, any solutions/suggestions are very welcome - happy to try anything!
My Python script (with credentials obfuscated):
*import pymssql
server = '[email protected]'
database = 'MyDatabase'
username = 'my_username'
password = 'my_password'
conn = pymssql.connect(server=server, user=username, password=password, database=database)
cursor = conn.cursor()
cursor.execute('SELECT Source FROM config.Columns ')
row = cursor.fetchone()
print(row)*
My Dockerfile:
# syntax=docker/dockerfile:1
FROM python:3.8-buster
WORKDIR /app
RUN apt-get update -y && \
apt-get install -y \
libpq-dev \
gcc \
python3-pip \
unixodbc-dev
RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
RUN curl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
RUN apt-get update
RUN ACCEPT_EULA=Y apt-get install -y --allow-unauthenticated msodbcsql17
RUN pip3 install pyodbc
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY . .
CMD [ "python", "-m" , "main", "run", "--host=0.0.0.0"]
azu-inf-drds02.example.com? (Also see How to connect external MS SQL server database from container.)python:3.8-buster? When working with Docker images you should always try to figure out which specific distro and version they're using, e.g.:docker run -it --rm python:3.8-buster cat /etc/os-releasetells you that it's Debian 10 (Buster), so you should be following the instructions for Install the Microsoft ODBC driver for SQL Server (Linux) # Debian to installmsodbcsql17/8for Debian 10.