首页 > 解决方案 > Docker:使用 localhost 而不是 db 连接到 PostgresDatabase

问题描述

我在使用 Docker 时遇到了问题。要从 Django 应用程序连接到 Postgres 数据库,我必须使用:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}

但是,要在我的 Pipenv shell 中通过 pytest 运行测试,我必须将 'Host': 从更改dblocalhost. 有没有一种方法可以让我始终使用 localhost?

码头工人组成:

version: '3'

services:
  db:
    image: postgres
    ports:
      - "5432:5432"
  web:
    build: .
    env_file: .env
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db
    container_name: test

Dockerfile:

# Pull base image
FROM python:3

# Set environment varibles
ENV PYTHONUNBUFFERED 1

# Set work directory
RUN mkdir /code
WORKDIR /code

# Install dependencies
RUN pip install --upgrade pip
RUN pip install pipenv
COPY ./Pipfile /code/Pipfile
RUN pipenv install --deploy --system --skip-lock --dev

# Define ENTRYPOINT
COPY ./docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
ENTRYPOINT ["/docker-entrypoint.sh"]

# Copy project
COPY . /code/

标签: djangodocker

解决方案


推荐阅读