我正在为django app创建一个docker-compose配置,Dockerfile构建成功但是当我编写它们时,django会返回一个问题 - 无法连接到postgres。
我运行docker-compose运行web bash,发现redis和posgres都无法连接。
我的docker-compose.yml文件
web:
build: .
ports:
- "8000:8000"
environment:
- 'DATABASE_HOST=db'
- 'DATABASE_NAME=mydb'
- 'DATABASE_USER=root'
- 'DATABASE_PASSWORD=root'
links:
- db
db:
image: postgres:9.1
当运行sudo docker-compose up时出现以下错误。
web_1 | File "/usr/local/lib/python2.7/site packages/django/db/backends/postgresql/base.py", line 175, in get_new_connection
web_1 | connection = Database.connect(**conn_params)
web_1 | File "/usr/local/lib/python2.7/site-packages/psycopg2/__init__.py", line 164, in connect
web_1 | conn = _connect(dsn, connection_factory=connection_factory, async=async)
web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused
web_1 | Is the server running on host "localhost" (::1) and accepting
web_1 | TCP/IP connections on port 5432?
web_1 | could not connect to server: Connection refused
web_1 | Is the server running on host "localhost" (127.0.0.1) and accepting
web_1 | TCP/IP connections on port 5432?
答案 0 :(得分:2)
我还使用docker-compose
构建了一个群集,它可能会帮助您解决问题(这里是repo)。您可以看到docker-compose.yml文件和django
settings文件(我标记了您需要的行)。
您也可以克隆此回购并获取django
,angular2
,postgresql
和nginx
个容器,这些容器已经链接在一起。
答案 1 :(得分:0)
您正在将您的Web容器与postgres容器相关联,但您没有定义数据库名称,密码和用户。
web:
build: .
ports:
- "8000:8000"
links:
- db
db:
restart: always
image: postgres:9.1
ports:
- "5432:5432"
volumes:
- pgvolume:/var/lib/postgresql/data
environment:
- POSTGRES_PASSWORD=root
- POSTGRES_DB= aiotadb
- POSTGRES_USER=root
data:
restart: always
image: postgres:9.1
volumes:
- /var/lib/postgresql
command: tail -f /dev/null
此外,如果您已在设置文件中定义数据库选项,则无需在Web容器中将其声明为env变量。
答案 2 :(得分:0)
version: '3'
services:
basicproject:
build: .
container_name: basicproject-container
depends_on:
- postgres
ports:
- "8000:8000"
postgres:
image: postgres:9.4
ports:
- "5432"
environment:
- POSTGRES_USER=test
- POSTGRES_PASSWORD=testing
- POSTGRES_DB=test_db
答案 3 :(得分:0)
在您的“网络”服务中添加依赖项,如下所示:
depends_on:
- db