python 无法连接django容器和postgresql容器

oyxsuwqo  于 2023-02-02  发布在  Python
关注(0)|答案(1)|浏览(114)

我试图连接django和postgresql内的docker容器,我无法做到这一点,我已经尝试了几件事,但没有为我工作,以下是我的docker组合文件

version: '3.8'
services:
  backend:
    build:
      context: .
      dockerfile: Dockerfile
    command: python manage.py runserver 0.0.0.0:8000
    ports:
      - 8000:8000
    volumes:
      - .:/app
    restart: on-failure
    depends_on:
      rabbitmq:
        condition: service_healthy

  postgres:
    image: postgres
    container_name: postgres
    volumes:
      - ./postgres-data:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=main
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=admin
    ports:
      - 5431:5431

  rabbitmq:
    image: rabbitmq:3-management
    container_name: rabbitmq
    hostname: rabbitmq
    ports:
      - 15673:15672

    environment:
      RABBITMQ_DEFAULT_USER: guest
      RABBITMQ_DEFAULT_PASS: guest
    healthcheck:
      test: rabbitmq-diagnostics check_port_connectivity
      interval: 30s
      timeout: 30s
      retries: 10
#  queue:
#    build:
#      context: .
#      dockerfile: Dockerfile
#    command: 'python consumer.py'
#    depends_on:
#      - db
#      - rabbitmq
#      - backend

在www.example.com中settings.py我有如下配置:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'main',
        'USER': 'postgres',
        'PASSWORD': 'admin',
        'HOST': 'postgres',
        'PORT': '5431'
    }
}

现在,当我运行docker-composite up命令时,我收到错误“django.db.utils.OperationalError:无法将主机名“postgres”转换为地址:名称解析暂时失败
我还尝试在www.example.com中将主机名更改为localhostsettings.py,然后显示此错误“端口5431上的TCP/IP连接?

n6lpvg4x

n6lpvg4x1#

当前postgres映像使用5432作为默认端口tho https://hub.docker.com/_/postgres
改为5432

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'main',
        'USER': 'postgres',
        'PASSWORD': 'admin',
        'HOST': 'postgres',
        'PORT': '5432',
    }
}

您的撰写网络似乎有问题。请再次尝试docker compose downdocker compose up。或者将links添加到您的撰写文件:

version: '3.8'
services:
  backend:
    build:
      context: .
      dockerfile: Dockerfile
    command: python manage.py runserver 0.0.0.0:8000
    ports:
      - 8000:8000
    volumes:
      - .:/app
    restart: on-failure
    depends_on:
      rabbitmq:
        condition: service_healthy
    links:
      - "postgres:postgres"

相关问题