我正在运行以下容器:
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b02d801f9aa3 development_mongo "docker-entrypoint.s…" 7 hours ago Up About an hour 0.0.0.0:50001->27017/tcp compose_mongo
2903bb830ea7 development_postgres "docker-entrypoint.s…" 7 hours ago Up About an hour 0.0.0.0:50000->5432/tcp compose_postgres
6ce3fe015a8f development_elastic "/usr/local/bin/dock…" 7 hours ago Up About an hour 0.0.0.0:50002->9200/tcp, 0.0.0.0:50003->9300/tcp compose_elastic
当我创建/运行具有入口点的 Docker 容器时python manage.py makemigrations
,Django 应用程序无法连接到 Postgres 容器:
$ docker run --name test1 repo/myapp:stage_1605191501
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/django/db/backends/base/base.py", line 217, in ensure_connection
self.connect()
File "/usr/local/lib/python3.6/dist-packages/django/db/backends/base/base.py", line 195, in connect
self.connection = self.get_new_connection(conn_params)
File "/usr/local/lib/python3.6/dist-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection
connection = Database.connect(**conn_params)
File "/usr/local/lib/python3.6/dist-packages/psycopg2/__init__.py", line 126, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
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 50000?
为什么无法连接,因为 Postgres 端口已经暴露给主机了?我遗漏了什么?
答案1
基本上,所有compose_*
容器都连接到不同的 Docker 网络,并且test1
与另一个网络相关联。
$ docker network inspect development_default | grep 'Name\|IPv4'
"Name": "development_default",
"Name": "compose_postgres",
"IPv4Address": "172.20.0.2/16",
"Name": "compose_elastic",
"IPv4Address": "172.20.0.4/16",
"Name": "compose_mongo",
"IPv4Address": "172.20.0.3/16",
这些容器是通过 Docker Compose 创建的,没有指定自定义网络。如果您的 Docker Compose 文件中没有定义自定义网络,docker 将创建一个自定义网络,该网络使用您构建环境所在的目录的名称。这就是为什么发展,用于生成这些容器的文件的目录名称,在development_default
为它们创建网络时使用。
执行命令时
$ docker run --name test1 repo/myapp:stage_1605191501
,未--network
指定,因此test1
将与默认bridge
网络相关联。compose_postgres
有 5432 端口暴露给主机网络并且与development_default
网络 (172.20.0.0/16) 关联。
解答(步骤):
- 提供静态 IP
compose_postgres
- 在 的图像内为 Django 应用程序定义定义此 IP,
test1
以便提供从应用程序到compose_postgres
数据库的连接 - 定义
development_default
为运行--network
时test1
docker run
进一步参考: