Connecting a Python Docker Container to MSSQL
One of the things I've struggled with lately was connecting to a Microsoft SQL Server database using python. The following pill is the simplest way I found to solve this issue.
First create a python file called main.py
from sqlalchemy import create_engine, inspect
server_url: str = "tcp:example-server.database.windows.net,1433"
datbase_name: str = "mydb"
username: str = "myusername"
password: str = "mypassword"
connection_str = f"mssql+pyodbc:///?odbc_connect=Server={server_url};Database={database_name};Uid{username};Pwd={password};Encrypt=yes;TrustServerCertificate=no;
db = create_engine(connection_str)
conn = db.connect()
inspector = inspect(self.db)
print([t for t in inspector.get_table_names()])
Add the following to your requirements.txt
pyodbc
sqlalchemy
Then create a Dockerfile, I'll be using this image as base:
FROM laudio/pyodbc:latest
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
EXPOSE 8000
ENV PORT 8000
CMD ["python", "main.py"]
Build the container
docker build -t mssql-example .
And run it with:
docker run -p 8000:8000 mssql-example