diff --git a/app.py b/app.py
index 8cea2ef..990974b 100644
--- a/app.py
+++ b/app.py
@@ -11,28 +11,44 @@ from bricktracker.socket import BrickSocket  # noqa: E402
 
 logger = logging.getLogger(__name__)
 
-# Create the Flask app
-app = Flask(__name__)
 
-# Setup the app
-setup_app(app)
+# Create the app
+# Using 'app' globally interferse with the teardown handlers of Flask
+def create_app(main: bool = False, /) -> Flask | BrickSocket:
+    # Create the Flask app
+    app = Flask(__name__)
 
-# Create the socket
-s = BrickSocket(
-    app,
-    threaded=not app.config['NO_THREADED_SOCKET'],
-)
+    # Setup the app
+    setup_app(app)
+
+    # Create the socket
+    s = BrickSocket(
+        app,
+        threaded=not app.config['NO_THREADED_SOCKET'],
+    )
+
+    if main:
+        return s
+    else:
+        return app
 
 
 if __name__ == '__main__':
+    s = create_app(True)
+
+    # This never happens, but makes the linter happy
+    if isinstance(s, Flask):
+        logger.critical('Cannot run locally with a Flask object, needs a BrickSocket. Use create_app(True) to return a BrickSocket')  # noqa: E501
+        exit(1)
+
     # Run the application
     logger.info('Starting BrickTracker on {host}:{port}'.format(
-        host=app.config['HOST'],
-        port=app.config['PORT'],
+        host=s.app.config['HOST'],
+        port=s.app.config['PORT'],
     ))
     s.socket.run(
-        app,
-        host=app.config['HOST'],
-        debug=app.config['DEBUG'],
-        port=app.config['PORT'],
+        s.app,
+        host=s.app.config['HOST'],
+        debug=s.app.config['DEBUG'],
+        port=s.app.config['PORT'],
     )
diff --git a/bricktracker/app.py b/bricktracker/app.py
index a1bfb27..8938e95 100644
--- a/bricktracker/app.py
+++ b/bricktracker/app.py
@@ -96,6 +96,6 @@ def setup_app(app: Flask) -> None:
         g.version = __version__
 
     # Make sure all connections are closed at the end
-    @app.teardown_appcontext
-    def close_connections(exception, /) -> None:
+    @app.teardown_request
+    def teardown_request(_: BaseException | None) -> None:
         close()
diff --git a/entrypoint.sh b/entrypoint.sh
index 7add85e..148c366 100755
--- a/entrypoint.sh
+++ b/entrypoint.sh
@@ -13,4 +13,4 @@ then
 fi
 
 # Execute the WSGI server
-gunicorn --bind "${BK_SERVER}:${BK_PORT}" "app:app" --worker-class "eventlet" "$@"
+gunicorn --bind "${BK_SERVER}:${BK_PORT}" "app:create_app()" --worker-class "eventlet" "$@"