I’m trying to run Flask app locally in the docker and I’m facing the following problem
app.py:
class App:
'''Base flask app'''
def __init__(self):
self.app = Flask(__name__)
@property
def flask_app(self) -> Flask:
'''Return flask app'''
return self.app
app_instance = App()
My Dockerfile:
...
CMD exec gunicorn --bind :8080 --workers 1 --threads 8 --timeout 0 app:app_instance.app
Error:
Failed to parse 'app_instance.app' as an attribute name or function call.
>Solution :
The error message indicates that gunicorn is unable to parse ‘app_instance.app’ correctly. This usually means that gunicorn is unable to find the application instance it needs to run.
When you use the gunicorn command, you need to specify the application module and the Flask application instance that gunicorn should serve. The format is typically module_name:instance_name.
In your Dockerfile, you are trying to pass app_instance.app to gunicorn, but since app_instance is an instance of the App class and not a module, this won’t work as expected.
One way to fix this issue is to make sure that your Flask application instance is available as a module-level variable that can be imported. You can modify your app.py to have a module-level variable that points to the Flask application. Here’s how you can adjust your app.py:
from flask import Flask
class App:
'''Base flask app'''
def __init__(self):
self.app = Flask(__name__)
@property
def flask_app(self) -> Flask:
'''Return flask app'''
return self.app
app_instance = App()
application = app_instance.flask_app # Make the Flask app available as 'application'
Then, in your Dockerfile, you would adjust the CMD to point to the application variable:
CMD exec gunicorn --bind :8080 --workers 1 --threads 8 --timeout 0 app:application
By doing this, you’re telling gunicorn to look for a variable named application in the app module, which is accessible at the module level and can be imported.