'pyodbc.OperationalError: ('08001', '[08001] [FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnect)')

Before posting this question I have gone through tons of posts however it did not helped me to fix my issue that is why I am asking this question and looking out for some help.

OS & Tools: Windows 10 having SQL Server, Docker and Python installed.

I am trying to create a docker image that would run the python script. The script has API endpoint (created using FastAPI) and SQL Server connection strings using pyodbc.

My ultimate goal is to run the docker image which would enable api that can access SQL Server and its tables.

Dockerfile is as follows:


WORKDIR /RSApp

COPY . /RSApp

COPY ./requirements.txt /requirements.txt

RUN apt-get update \
 && apt-get install unixodbc -y \
 && apt-get install unixodbc-dev -y \
 && apt-get install freetds-dev -y \
 && apt-get install freetds-bin -y \
 && apt-get install tdsodbc -y \
 && apt-get install --reinstall build-essential -y

# populate "ocbcinst.ini"
RUN echo "[FreeTDS]\n\
            Description = FreeTDS unixODBC Driver\n\
            Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so\n\
            Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so \n\
            UsageCount=1" >> /etc/odbcinst.ini

RUN echo "[DB1] \n\
            Description = My DSN \n\
            Driver = FreeTDS \n\
            Database = DB1 \n\
            Servername = mssql \n\
            TDS_Version = 8.0" >> /etc/odbc.ini

RUN echo "[mssql] \n\
            host = <hostname> \n\
            instance = SQLEXPRESS \n\
            port = 1433" >> /etc/freetds/freetds.conf

RUN pip install -r requirements.txt

EXPOSE 8000

CMD [ "uvicorn", "main:app", "--host", "0.0.0.0"]

PYODBC Connection is as follows:

connection = pyodbc.connect("DRIVER={FreeTDS}; \
                                    SERVER='<servername>'; \
                                    PORT=1433; \
                                    DATABASE={DB1}; \
                                    TDS_Version = '8.0'")

When I run the docker image and try to access the api I get the following error:

pyodbc.OperationalError: ('08001', '[08001] [FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnect)')

Any help is much appreciated, thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source