Docker- django在连接到postgres时抛出错误:psycopg2.OperationalError:无法连接到服务器:连接被拒绝 [英] Docker- django throws error while connecting to postgres: psycopg2.OperationalError: could not connect to server: Connection refused

查看:1314
本文介绍了Docker- django在连接到postgres时抛出错误:psycopg2.OperationalError:无法连接到服务器:连接被拒绝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对我的Django-postgres应用进行docker化。
我的Dockerfile是:

I am trying to dockerize my Django-postgres app. My Dockerfile is:

FROM python:3

ENV PYTHONUNBUFFERED 1

RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/

我的docker-compose.yml是:

My docker-compose.yml is:

version: '3'

services:
  web:
    build: .
    command: python app/manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db
  db:
    image: postgres
    ports:
      - "5432:5432"
    environment:
      POSTGRES_PASSWORD: password

和我的设置.py具有以下数据库代码:

and my settings .py has the following database code:

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

我的数据库和Web容器已启动,但是当我运行时:
docker-compose run web python manage.py migration
我遇到了错误:

My db and web containers are up but when I run: docker-compose run web python manage.py migrate I am getting the error:


psycopg2.OperationalError:无法连接到服务器:连接被拒绝
服务器是否在主机 0.0.0.0上运行并在端口5432上接受
TCP / IP连接?

psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "0.0.0.0" and accepting TCP/IP connections on port 5432?

如何使我的容器通信?

推荐答案

更改主机到:

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

0.0.0.0 不是有效的 IP ,除了您需要使用<$ c连接$ c>服务名称,因为撰写会为您解决该问题

0.0.0.0 is not a valid IP, beside you need to connect using the service name since compose will resolve it for you

这篇关于Docker- django在连接到postgres时抛出错误:psycopg2.OperationalError:无法连接到服务器:连接被拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆