gpt4 book ai didi

postgresql - 为什么我的Flask服务器无法使用docker-compose与postgres数据库对话?

转载 作者:行者123 更新时间:2023-12-02 19:52:43 24 4
gpt4 key购买 nike

我已经在下面发布了相关文件。一切都按预期构建,但是当尝试使用SQLAlchemy进行数据库调用时,我总是遇到以下错误:
OperationalError: (psycopg2.OperationalError) could not translate host name "db" to address: Name or service not known
sqlalchemy使用的字符串是(如.env.web.dev中给出的):postgres://postgres:postgres@db:5432/spaceofmotion

我究竟做错了什么?

docker-compose.yml:

version: '3'

services:
db:
container_name: db
ports:
- '5432:5432'
expose:
- '5432'
build:
context: ./
dockerfile: Dockerfile.postgres
networks:
- db_web

web:
container_name: web
restart: always
build:
context: ../
dockerfile: Dockerfile.web
ports:
- '5000:5000'
env_file:
- ./.env.web.dev
networks:
- db_web
depends_on:
- db
- redis
- celery

redis:
image: 'redis:5.0.7-buster'
container_name: redis
command: redis-server
ports:
- '6379:6379'

celery:
container_name: celery
build:
context: ../
dockerfile: Dockerfile.celery
env_file:
- ./.env.celery.dev
command: celery worker -A a.celery --loglevel=info
depends_on:
- redis

client:
container_name: react-app
build:
context: ../a/client
dockerfile: Dockerfile.client
volumes:
- '../a/client:/src/app'
- '/src/app/node_modules'
ports:
- '3000:3000'
depends_on:
- "web"
environment:
- NODE_ENV=development
- HOST_URL=http://localhost:5000

networks:
db_web:
driver: bridge

Dockerfile.postgres:
FROM postgres:latest

ENV POSTGRES_DB spaceofmotion
ENV POSTGRES_USER postgres
ENV POSTGRES_PASSWORD postgres

COPY ./spaceofmotion-db.sql /
COPY ./docker-entrypoint-initdb.d/restore-database.sh /docker-entrypoint-initdb.d/

restore-database.sh:
file="/spaceofmotion-db.sql"
psql -U postgres spaceofmotion < "$file"

Dockerfile.web:
FROM python:3.7-slim-buster

RUN apt-get update
RUN apt-get -y install python-pip libpq-dev python-dev && \
pip install --upgrade pip && \
pip install psycopg2

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

COPY . /app
WORKDIR /app

RUN pip install -r requirements.txt

CMD ["python", "manage.py", "runserver"]

.env.web.dev:
DATABASE_URL=postgres://postgres:postgres@db:5432/spaceofmotion
... <other config vars> ...

最佳答案

这是您的celery容器专用的吗?

您的db容器声明

networks:
- db_web

但是 celery容器没有这样的声明;那意味着 it will be on the default network Compose creates for you。由于这两个容器不在同一网络上,因此它们无法相互连接。

使用Compose管理的 default网络没有任何问题,尤其是对于常规Web应用程序,我建议删除整个文件中的所有 networks:块。 (您也不需要指定 container_name:,因为Compose会自行提供合​​理的名称。)

关于postgresql - 为什么我的Flask服务器无法使用docker-compose与postgres数据库对话?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59604772/

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