docker compose无法使用django

时间:2017-10-27 10:44:07

标签: django postgresql docker docker-compose

我的django app无法连接到postgresql。我使用Dockerfile进行django并使用docker-compose和postgres官方图像进行构建。

搬运工-compose.yml

version: '2'

services:
db:
    image: eg_postgresql
    expose:
        - 5432
    environment:
        - POSTGRES_PASSWORD=docker
        - POSTGRES_USER=docker
        - POSTGRES_DB=postgres
web:
    build: .
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes:
        - .:/test_application
    ports:
        - "8000:8000"
    links:
        - "db:db"
    environment:
        - DATABASE_URL=postgres://docker:docker@db:5432/postgres
        - DJANGO_SECRET_KEY=x7-g-xu^h5k%h8860!7ksn=@)7q9frn9_l6tmefvf)y=0)d!uh 

输出:

    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Cannot assign requested address
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?

docker-compose ps

ubuntu@ip-172-31-7-117:~/dj1/helloworld$ sudo docker-compose ps
  Name                    Command               State           Ports         

----------------------------------------------------------------------------------
helloworld_db_1    /usr/lib/postgresql/9.3/bi ...   Up      5432/tcp              

helloworld_web_1   python3 manage.py runserve ...   Up      0.0.0.0:8000->8000/tcp
在app settings.py

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

我尝试过多种方式连接,但问题是相同的......

1 个答案:

答案 0 :(得分:0)

尝试使用端口替换公开: - 5432 以用于您的数据库服务 - " 5432:5432"