连接到Docker容器上的PostgreSQL数据库 [英] Connect to a PostgreSQL database on a Docker container
问题描述
我想在单独的Docker容器上运行具有PostgreSQL数据库和Django支持的REST API的应用程序。到目前为止,API已在连接SQLite数据库的Docker上运行,但是现在我要连接到PostgreSQL数据库遇到了麻烦。
I want to run an application with a PostgreSQL database and a REST API powered by Django on separate Docker containers. So far the API has been running on Docker connecting to a SQLite database, but I'm having trouble now that I want to connect to a PostgreSQL database instead.
Docker的 docker-compose.yml
文件:
Docker's docker-compose.yml
file:
version: '2'
services:
postgres:
image: postgres
api:
build: .
command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:1337"
volumes:
- .:/usr/src/app
ports:
- "1337:1337"
depends_on:
- postgres
Django的 settings.py
(根据默认设置,使用基本 postgres
图像所使用的默认设置文档):
Django's settings.py
(using the default settings which the base postgres
image works with according to the documentation):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'wgomanager',
'USER': 'postgres',
'PASSWORD': 'mysecretpassword',
'HOST': 'localhost',
'PORT': '5432',
}
}
当我使用 docker-compose up
启动应用程序时,最终会引发此错误:
When I launch the application with docker-compose up
eventually this error is thrown:
api_1 | connection = Database.connect(**conn_params)
api_1 | File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect
api_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
api_1 | django.db.utils.OperationalError: could not connect to server: Connection refused
api_1 | Is the server running on host "localhost" (::1) and accepting
api_1 | TCP/IP connections on port 5432?
api_1 | could not connect to server: Connection refused
api_1 | Is the server running on host "localhost" (127.0.0.1) and accepting
api_1 | TCP/IP connections on port 5432?
api_1 |
orchestrator_api_1 exited with code 1
我在做什么错了?
推荐答案
使用docker-compose时,您可以通过主机名发现服务。您的数据库服务是用标签 postgres 定义的。在应用程序配置中将其用作主机名。
When using docker-compose, you "discover" services via hostname. Your database service is defined with label postgres. Use it as a hostname in your application cofiguration.
密码和数据库名称也必须与您的应用程序配置同步。这是通过postgres服务的环境变量完成的:
Also password and DB name must be in sync with your app config. This is done via environment variables for postgres service:
services:
postgres:
environment:
- POSTGRES_PASSWORD: "mysecretpassword"
- POSTGRES_DB: "wgomanager"
# rest of docker-compose.yml
请参阅图像文档,了解各种环境。 vars影响服务配置。
Reffer to image docs on how various env. vars affect service configuration.
这篇关于连接到Docker容器上的PostgreSQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!