在Fly.io上为Django配置Postgres数据库时遇主机解析错误求助
解决Fly.io + Django + Postgres本地migrate时的"Unknown host"错误
你遇到的psycopg2.OperationalError: could not translate host name "top2.nearest.of.MYAPP-pg.internal" to address: Unknown host错误,核心原因是:top2.nearest.of.MYAPP-pg.internal是Fly.io内网专用的DNS域名,只有Fly.io的服务器集群内部能解析,你的本地机器无法识别这个域名。
解决方案1:在Fly.io远程环境执行migrate
这是最可靠的方式,直接在应用的远程容器中运行数据库迁移:
- 执行命令进入远程shell:
flyctl ssh console - 在远程shell中运行迁移:
python manage.py migrate
解决方案2:使用Postgres外部连接串在本地执行migrate
如果你需要在本地运行migrate,可以使用Fly.io提供的Postgres外部连接地址:
- 获取外部连接URL:
执行后会输出一个类似flyctl postgres connect -a MYAPP-pg --urlpostgres://user:password@external-host.flycast:5432/dbname的连接串 - 本地临时设置环境变量(根据系统不同):
- Windows(命令提示符):
set DATABASE_URL=上面获取的外部连接串 - Mac/Linux:
export DATABASE_URL=上面获取的外部连接串
- Windows(命令提示符):
- 然后在本地运行:
python manage.py migrate
额外修正:移除fly.toml中多余的Postgres服务配置
你在fly.toml中添加的指向5432端口的[[services]]配置是不必要的,Fly.io的Postgres集群已经自带网络配置,这部分配置会和应用本身的服务冲突,建议删除:
# 删掉以下内容 [[services]] internal_port = 5432 # Postgres instance protocol = "tcp" # Open port 10000 for plaintext connections. [[services.ports]] handlers = [] port = 10000
内容的提问来源于stack exchange,提问作者ultreian
相关产品推荐
相关产品推荐

