在Heroku上执行FastAPI数据库迁移时出现“bash: alembic: command not found”错误的排查求助
Let's break down why you're hitting this error and walk through how to fix it:
The Root Cause
Heroku's dynos don't come pre-installed with Alembic—your project has to explicitly tell Heroku to install it as a dependency. Right now, when you run heroku run "alembic upgrade head", the dyno's environment has no idea what the alembic command is because it wasn't installed during deployment.
Step-by-Step Fixes
Add Alembic to your requirements.txt
Make sure yourrequirements.txtincludes Alembic and all related dependencies your migration setup needs. At minimum, you should have lines like:alembic>=1.12.0 sqlalchemy>=2.0.0 psycopg2-binary>=2.9.0 # Use this instead of psycopg2 for better Heroku compatibility fastapi>=0.100.0 pydantic-settings>=2.0.0 # If you're using Pydantic for environment settingsNote:
psycopg2-binaryis preferred over standardpsycopg2here because it avoids compilation issues on Heroku's build servers.Re-deploy your code to Heroku
Push your updatedrequirements.txtto your Heroku remote to trigger a new build with the missing dependencies:git add requirements.txt git commit -m "Add alembic and required dependencies" git push heroku mainHeroku will automatically install all listed packages during the build process.
Run the migration command (with a fallback if needed)
After redeploying, try your original command again:heroku run "alembic upgrade head"If you still run into path-related issues, use the Python module syntax instead—this bypasses any environment path configuration problems:
heroku run "python -m alembic upgrade head"
Extra Checks for Your Setup
Verify your settings pull from Heroku's environment variables
Yourenv.pyusessettingsto get database credentials, so make sure yourapp/config.pycorrectly reads Heroku's built-inDATABASE_URLvariable (Heroku sets this automatically for your Postgres add-on). For example:# In app/config.py from pydantic_settings import BaseSettings class Settings(BaseSettings): database_url: str = "" # Automatically pulls from DATABASE_URL env var class Config: env_file = ".env" # For local development, ignored on HerokuThis ensures your migration script connects to the correct Heroku Postgres instance instead of your local database.
Confirm your alembic.ini configuration
Youralembic.inihas a local database URL, but since yourenv.pyoverrides this with the settings value, that's fine. Just double-check thatscript_location = alembicis set correctly (which it is in your provided file) so Alembic can find your migration scripts.
内容的提问来源于stack exchange,提问作者znowusiejeblem

