I have a basic flask application that uses postgresql for database and SQLAlchemy for ORM. I want to deploy this application using docker. The project directory looks something like this:
.
├── app.py
├── database
│ ├── config.py
│ └── models.py
├── docker-compose.yml
├── Dockerfile
└── requirements.txt
I have database table definitions in models.py and database configuration config.py
config.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://flask:flask123@db:5432/flask_db'
db = SQLAlchemy(app)
I then start the app and create database tables with this in app.py
if __name__ == '__main__':
with app.app_context():
db.create_all()
db.session.commit()
app.run(debug=True)
Dockerfile:
FROM python:3
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["flask", "run", "--host", "0.0.0.0"]
docker-compose:
version: "1"
services:
db:
image: postgres:latest
restart: always
hostname: postgres
environment:
POSTGRES_USER: flask
POSTGRES_PASSWORD: flask123
POSTGRES_DB: flask_db
ports:
- "5432:5432"
networks:
- my_network
flask_app:
restart: always
build:
context: .
ports:
- "5000:5000"
depends_on:
- db
networks:
- my_network
networks:
my_network:
When I docker compose up, everything seems to work fine, the containers are up and I can reach my application from localhost:5000. However any api request involving getting data from the database returns an error and when I inspect the database container logs I see the following error for database queries:
ERROR: relation "users" does not exist
I suspect there is something wrong with the connections or the order the containers are started but I cant seem to find what is causing database tables not created.
if __name__ == "__main__"code is going to run when usingflask run. If you want to perform initialization, either use an app factory or register abefore_first_requestfunction.