gpt4 book ai didi

django 容器无法访问 postgres 容器

转载 作者:行者123 更新时间:2023-12-02 18:07:09 27 4
gpt4 key购买 nike

我正在尝试使用 docker-compose 连接我的数据库和我的 django rest api。但是,我的 Django 容器给了我这个错误:

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

Postgres 正常启动,我可以使用终端在本地访问它。我只是不确定为什么我的 django 容器无法连接。
$ psql -h 0.0.0.0 -p 5432 -U bli1 -d redribbon
Password for user bli1:
psql (12.1)
Type "help" for help.

在我的 settings.py 内对于 Django,这是我的数据库值
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": "redribbon",
"USER": "bli1",
"PASSWORD": "password",
"HOST": "0.0.0.0",
"PORT": "5432",
}
}

docker-compose.yml
version: "3"
services:
postgres:
image: postgres:latest
restart: always
ports:
- "5432:5432"
volumes:
- ./pgdata:/var/lib/postgresql/data/
environment:
POSTGRES_DB: redribbon
POSTGRES_USER: bli1
POSTGRES_PASSWORD: password
api:
build:
dockerfile: Dockerfile.dev
context: ./redribbon-api
command: python manage.py runserver 0.0.0.0:8000
volumes:
- ./redribbon-api/api:/usr/src/api
depends_on:
- postgres
ports:
- "8000:8000"

更新:

在 django 容器中,我能够 ping postgres 并将其作为响应
# ping postgres
PING postgres (172.19.0.2) 56(84) bytes of data.
64 bytes from redribbon_postgres_1.redribbon_default (172.19.0.2): icmp_seq=1 ttl=64 time=0.175 ms
64 bytes from redribbon_postgres_1.redribbon_default (172.19.0.2): icmp_seq=2 ttl=64 time=0.096 ms
64 bytes from redribbon_postgres_1.redribbon_default (172.19.0.2): icmp_seq=3 ttl=64 time=0.097 ms

我什至尝试改变 "HOST": "0.0.0.0","HOST": "postgres",在我的 settings.py但我收到与上述相同的错误

最佳答案

本地文件

version: '3'

volumes:
local_postgres_data: {}
local_postgres_data_backups: {}

services:
django:
build:
context: .
dockerfile: ./compose/local/django/Dockerfile
image: apkomat_local_django
container_name: django
depends_on:
- postgres
volumes:
- .:/app:z
env_file:
- ./.envs/.local/.django
- ./.envs/.local/.postgres
ports:
- "8000:8000"
command: /start

postgres:
build:
context: .
dockerfile: ./compose/production/postgres/Dockerfile
image: apkomat_production_postgres
container_name: postgres
volumes:
- local_postgres_data:/var/lib/postgresql/data:Z
- local_postgres_data_backups:/backups:z
env_file:
- ./.envs/.local/.postgres
这是我的本地 docker-compose 配置。
 depends_on:
- postgres
此设置可确保您的 Django 服务在 postgres 准备好接受连接之前不会启动。要使用这些配置运行您的应用程序,请使用
docker-compose -f local.yml up 

关于django 容器无法访问 postgres 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60158583/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com