【发布时间】:2021-09-14 10:43:37
【问题描述】:
我发现在容器化环境中处理数据库迁移的工作流程令人困惑。我有一个带有附加数据库的 Web API。 API 在一个容器中运行,数据库在另一个容器中运行。项目文件结构如下
.
├── docker-compose.yml
├── Dockerfile
└── app
| ├── __init__.py
| ├── database
| | ├── alembic/
| | ├── __init__.py
| | ├── db.py
| | └── models.py
| ├── other
| ├── source
| └── files
├── other
└── files
为了让 API 容器能够访问数据库,ini 文件中的 sqlalchemy.url 设置为:
postgresql://{username}:{password}@db:5432/{database}
但是当我想进行迁移时,例如添加一个表列,我会将app/database/models.py更改目录中的模型更改为app/database并运行alembic revision --autogenerate -m "Description"。这是问题发生的地方,我收到错误:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name "db" to address: Name or service not known
如果我将主机名更改为 localhost 它可以工作,但是 docker-compose 会中断,因为它必须引用容器名称。
此工作流程似乎不正确。人们如何在使用容器的项目中使用数据库?
docker-compose.yml 文件如下所示:
version: "3"
services:
db:
image: postgres
ports:
- "5432:5432"
environment:
- POSTGRES_USER=username
- POSTGRES_PASSWORD=password
- POSTGRES_DB=database
app:
build: .
command: bash -c "cd app/database && alembic upgrade head && cd ../.. && python app/main.py"
volumes:
- .:/code
ports:
- "5000:5000"
depends_on:
- db
【问题讨论】:
标签: python docker sqlalchemy alembic