如何在Django项目中使用Docker compose连接到本地PostGIS(PostgreS)数据库



我需要连接到计算机中现有的数据库。当我用postgis镜像创建数据库服务时,它会在docker容器中创建一个新的数据库。但我需要连接到本地的。有可能吗?docker compose.yml:

  version: '3'
  services:
      build: ./
      command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py collectstatic --noinput --i rest_framework && gunicorn orion-amr.wsgi:application --bind 0.0.0.0:8000 --workers=2"
      ports:
        - "${webport}:8000"
      env_file:
        - ./.env

设置.py

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': os.environ.get('pgdatabase'),
        'USER': os.environ.get('pguser'),
        'PASSWORD': os.environ.get('pgpassword'),
        'HOST': os.environ.get('pghostname'),
        'PORT': '5432',
    }
}

.env文件:

pgport=5432
webport=8000
SECRET_KEY=z)mf(y#w7-_8y1)0(v*n@w@lzf)!0=g_rj5$%1w6g-t!7nbk05
pgdatabase=amr_or
pgpassword=root
pghostname=localhost
pguser=postgres
DEBUG=

现在我有这个错误:

web_1  | django.db.utils.OperationalError: could not connect to server: Connection refused
web_1  |        Is the server running on host "localhost" (127.0.0.1) and accepting
web_1  |        TCP/IP connections on port 5432?
web_1  | could not connect to server: Cannot assign requested address
web_1  |        Is the server running on host "localhost" (::1) and accepting
web_1  |        TCP/IP connections on port 5432

我真的希望你没有把你真正的SECRET_KEY暴露在互联网上。如果你改了,别忘了改。

如果我没记错(根据你今年早些时候问的一个问题(,你正在运行Docker for Windows。看看这里的文件,上面写着

主机有一个正在更改的IP地址(如果您没有网络访问权限,则没有(。从18.03开始,我们建议连接到特殊的DNS名称host.docker.internal,该名称解析为主机使用的内部IP地址。这是出于开发目的,不会在Docker Desktop for Windows之外的生产环境中工作。

因此,将pghostname设置为host.docker.internal,而不是localhost

既然你声明;需要连接到(您的(计算机中的现有数据库";,我将继续假设您这样做是为了开发目的,所以这应该足够了。

但是,在生产中,您需要在一个单独的容器中运行数据库并映射卷。

最新更新