While building a Dockerfile I'm trying to create a timescale database engine using a SQLAlchemy code. I used the official TimescaleDB image and after that I installed python in the same Dockerfile to start SQLAlchemy code with CMD command. In my SQLAlchemy Code I create an engine and start a session to insert data in created database as follow:
sqlalchemy.py
data = X
engine = create_engine("dbms://username:password@server:port/database")
Session = sessionmaker(bind = engine)
Base = declarative_base()
class Query(Base):
__tablename__ = "X"
X = Column(Integer, primary_key = "True")
def __init__(self, X):
self.X = X
Base.metadata.create_all(engine)
session = Session()
session.add(Query(data))
session.commit()
session.close()
sqlalchemy.sh
#!/bin/bash
python3 ./sqlalchemy.py
Dockerfile:
FROM timescale/timescaledb:latest-pg12
ENV POSTGRES_PASSWORD=X
ENV POSTGRES_USER=X
RUN apk add --update --no-cache python3 && ln -sf python3 /usr/bin/python
RUN python3 -m ensurepip
RUN pip3 install --no-cache --upgrade pip setuptools
COPY ./pathcopyfrom ./pathcopyto
WORKDIR ./pathcopyto
CMD ["./sqlalchemy.sh"]
But I get the error message:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) server closed the connection
unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
I just removed CMD command in my Dockerfile. After that I got into the Container with docker exec -it psql -U postgres
. I ran the SQLAlchemy code. It worked fine.
I don't understand what is leading me to the problem. I kept trying to start the Database Engine in my python code with a time delay and built Dockerfile with CMD ["./sqlalchemy.sh"]
It did not work.
Does anyone know how to solve this problem?