我正在尝试在 docker-compose 上运行带有 postgres 数据库的 django 应用程序。我可以完美运行它,但是一旦我发出发布请求,我就会收到此错误:
失败的测试/test_email.py::TestUser::test_list_to - requests.exceptions.ConnectionError:HTTPConnectionPool(主机='172.17.0.1',端口=8080):超过最大重试次数,网址:/api/v1/customers/516c7146- afc0-463b-be0e-7df01e8a86f6/emails (由 NewConnectionError 引起('
这是我的 docker-compose 文件:
version: "3"
services:
db:
image: postgres:latest
restart: always
environment:
POSTGRES_PASSWORD: verySecretPassword
POSTGRES_USER: administrator
POSTGRES_DB: project
volumes:
- ./data/db:/var/lib/postgresql/data
web:
build: .
restart: always
ports:
- "8080:8080"
depends_on:
- db
environment:
DATABASE_URL: postgresql://administrator:verySecretPassword@db:5432/project
volumes:
- .:/app
这是我的 Dockerfile:
# Use the official Python image as a base image
FROM python:3.10
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# Set the working directory
WORKDIR /app
# Install Django and Django REST Framework
RUN pip install --no-cache-dir django djangorestframework
# Install system dependencies for psycopg2 (PostgreSQL client)
RUN apt-get update && \
apt-get install -y postgresql-client
# Copy the requirements file and install dependencies
COPY requirements.txt /app/
RUN pip install --no-cache-dir -r requirements.txt
# Copy the Django project files to the container
COPY . /app/
# Install system dependencies for psycopg2 (if necessary)
RUN apt-get update && \
apt-get install -y libpq-dev gcc
# Install psycopg2 (or psycopg2-binary)
RUN pip install --no-cache-dir psycopg2-binary==2.8.6
# Copy the input.json file to the container
COPY input/input.json /app/input/
EXPOSE 8080
# Run Django development server
# CMD ["python3", "manage.py", "runserver", "0.0.0.0:8080"]
CMD ["bash", "-c", "sleep 10 && python3 manage.py makemigrations && python3 manage.py migrate && python3 manage.py runserver 0.0.0.0:8080"]
我的settings.py文件(仅限数据库部分)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'assignment',
'USER': 'administrator',
'PASSWORD': 'verySecretPassword',
'HOST': 'db',
'PORT': '5432',
}
}
有什么想法吗?先谢谢你了
在您的撰写文件中尝试此操作。我在 .env 文件中设置了环境变量。
db:
image: postgres:latest
volumes:
- postgres_data:/var/lib/postgresql/data/
environment:
- POSTGRES_HOST_AUTH_METHOD=trust
env_file:
- ./.env