You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django+Postgres执行makemigrations/migrate时出现主机名解析错误求助

Django迁移时PostgreSQL主机名解析失败问题解决

遇到的错误

  • 执行makemigrations命令触发警告:
/home/azeez/bendownselect/venv/lib/python3.12/site-packages/django/core/management/commands/makemigrations.py:160: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "postgres" to address: Temporary failure in name resolution
  • 执行migrate命令触发错误:
django.db.utils.OperationalError: could not translate host name "postgres" to address: Temporary failure in name resolution

当前数据库配置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': env("POSTGRES_DB"),
        'USER': env("POSTGRES_USER"),
        'PASSWORD': env("POSTGRES_PASSWORD"),
        'HOST': env("POSTGRES_HOST"),
        'PORT': env("POSTGRES_PORT"),  
    }
}

解决步骤

  1. 核对POSTGRES_HOST环境变量

    • 本地PostgreSQL:将POSTGRES_HOST设为localhost或127.0.0.1
    • Docker部署场景:确保PostgreSQL容器名称为postgres,且Django容器与它在同一Docker网络;若网络连通有问题,可直接替换为PostgreSQL容器的IP地址
    • 远程数据库:填写正确的公网IP或可正常解析的域名
  2. 测试主机名解析能力
    在运行Django的环境中执行以下命令,验证postgres主机名是否能被解析:

    ping postgres
    # 或用nslookup排查DNS问题
    nslookup postgres
    

    若解析失败,说明DNS配置异常或主机名不存在,需调整主机名或修复DNS设置。

  3. 确认PostgreSQL服务状态

    • 本地环境:检查服务是否启动
      # Ubuntu/Debian
      sudo systemctl status postgresql
      # macOS(Homebrew安装)
      brew services list | grep postgresql
      
    • Docker环境:检查容器是否正常运行
      docker ps
      
      确保PostgreSQL容器处于Up状态。
  4. 排查网络访问限制
    若使用远程数据库,确认目标主机的防火墙、安全组已开放PostgreSQL默认端口(5432),允许当前机器的IP访问。

内容的提问来源于stack exchange,提问作者SifuSherif

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 17:00:58