I am trying to connect to a database within a Docker container, however, I get the following error:
OperationalError: (pymssql._pymssql.OperationalError) (20009, b'DB-Lib error message 20009, severity 9:\nUnable to connect: Adaptive Server is unavailable or does not exist (DB)\n')
(Background on this error at: https://sqlalche.me/e/20/e3q8)
The code works fine as a standalone script, e.g. I can connect to the database fine using no Docker container. However, when I try to connect via a Docker container the above error arises. My code:
from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.engine import reflection
from sqlalchemy.orm import sessionmaker, DeclarativeBase
import os
# Get environment variables
user = os.getenv('USER', 'user')
password = os.getenv('PASSWORD', 'password')
host = os.getenv('HOST', 'DB')
database = os.getenv('DB', 'Epicor')
port = os.getenv('PORT', 5432)
SQLALCHEMY_DATABASE_URL = f"mssql+pymssql://{user}:{password}@{host}:{port}/{database}"
engine = create_engine(
SQLALCHEMY_DATABASE_URL
# Uncomment for debug info of db creation
# echo=True
)
(Part of) my Dockerfile:
extra_hosts:
- "host.docker.internal:host-gateway"
version: "3"
services:
database:
build: ./database
ports:
- "5432:5432"
networks:
- test
restart: unless-stopped
extra_hosts:
- "host.docker.internal:host-gateway"
Any help would be appreciated :)
I have tried to google the problem before, I found a SO post detailing the exact same problem, but the solution that was given I tried to apply in my Docker file (extra_hosts) but to no avail. The solution also did not work for the OP of that post