python – Django无法连接到Docker设置中的Postgres

我在Docker中设置了一个使用Django和Postgres的应用程序.我无法从应用程序连接到Postgres.我跑的时候:

> docker-compose运行web python manage.py runserver
> docker-compose运行web python manage.py migrate

我收到以下错误:

django.db.utils.OperationalError: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

这是我的Dockerfile:

FROM python:2.7

ADD requirements.txt /app/requirements.txt

WORKDIR /app/

RUN pip install -r requirements.txt

我的docker-compose.yml:

version: '2'
services:
  db:
    image: postgres:9.4
    hostname: db
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=postgres
    ports:
      - "5432:5432"

  web:
    build:
      context: .
      dockerfile: Dockerfile
    hostname: web
    volumes:
      - .:/app
    ports:
      - "8000:8000"
    links:
      - db
    depends_on:
      - db
    command:
      python manage.py runserver 0.0.0.0:8000

和Django中的数据库设置:

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

docker ps -a显示:

e9df7e1644ce        web             "python manage.py ..."   About a minute ago   Up About a minute          0.0.0.0:8000->8000/tcp   web_1
60801d3256e4        postgres:9.4        "docker-entrypoint..."   About a minute ago   Up About a minute          0.0.0.0:5432->5432/tcp   db_1

Django v1.10.5
Docker for Mac v1.13.1
docker-compose v 1.11.1

这是日志:

>网络:https://gist.github.com/steven-mercatante/912ca964fd05bee2c835b1ac5586c154
> db:https://gist.github.com/steven-mercatante/4c9a03bfc4f2e90f4b9931bdc185652f

最佳答案
原来问题是Postgres在启动Django应用程序之前没有完全旋转.在启动Web服务器之前等待几秒钟就可以轻松解决这个问题.我将我的Web服务命令设置为./bin/boot.sh,该文件的内容为:

#!/bin/sh

# wait for Postgres to start
sleep 10

python manage.py migrate

python manage.py runserver 0.0.0.0:8000

编辑

这个方法可能不够好,这取决于你的应用程序 – 大多数时候,睡眠10秒对我有效,但是postgres可能需要11秒才能启动.这是一个改进的bash文件,我从这个example中获取了一个函数.

#!/bin/bash

# wait for Postgres to start
function postgres_ready(){
python << END
import sys
import psycopg2
try:
    conn = psycopg2.connect(dbname="postgres", user="postgres", password="postgres", host="postgres")
except psycopg2.OperationalError:
    sys.exit(-1)
sys.exit(0)
END
}

until postgres_ready; do
  >&2 echo "Postgres is unavailable - sleeping"
  sleep 1
done

python manage.py migrate

gunicorn pft.wsgi:application -w 2 -b 0.0.0.0:8000 --reload

转载注明原文:python – Django无法连接到Docker设置中的Postgres - 代码日志