我正在尝试使用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
中,这是我的数据库值
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
,但遇到与上述相同的错误
答案 0 :(得分:0)
local.yml
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