使用pika,如何连接运行在docker中的rabbitmq,从docker开始-与外部网络连接?
问题描述
我有以下docker合成文件:
version: '2.3'
networks:
default: { external: true, name: $NETWORK_NAME } # NETWORK_NAME in .env file is `uv_atp_network`.
services:
car_parts_segmentor:
# container_name: uv-car-parts-segmentation
image: "uv-car-parts-segmentation:latest"
ports:
- "8080:8080"
volumes:
- ../../../../uv-car-parts-segmentation/configs:/uveye/configs
- /isilon/:/isilon/
# - local_data_folder:local_data_folder
command: "--run_service rabbit"
runtime: nvidia
depends_on:
rabbitmq_local:
condition: service_started
links:
- rabbitmq_local
restart: always
rabbitmq_local:
image: 'rabbitmq:3.6-management-alpine'
container_name: "rabbitmq"
ports:
- ${RABBIT_PORT:?unspecified_rabbit_port}:5672
- ${RABBIT_MANAGEMENT_PORT:?unspecified_rabbit_management_port}:15672
此程序运行时,docker ps
显示
21400efd6493 uv-car-parts-segmentation:latest "python /uveye/app/m…" 5 seconds ago Up 1 second 0.0.0.0:8080->8080/tcp, :::8080->8080/tcp joint_car_parts_segmentor_1
bf4ab8581f1f rabbitmq:3.6-management-alpine "docker-entrypoint.s…" 5 seconds ago Up 4 seconds 4369/tcp, 5671/tcp, 0.0.0.0:5672->5672/tcp, :::5672->5672/tcp, 15671/tcp, 25672/tcp, 0.0.0.0:15672->15672/tcp, :::15672->15672/tcp rabbitmq
我要创建到该Rabbitmq的连接。用户:通过是guest:guest
。
我无法执行此操作,在所有情况下,AMQPConnectionError
信息都非常贫乏:
下面的代码在另一个不相关的容器中运行。
connection = pika.BlockingConnection(pika.URLParameters("amqp://guest:guest@rabbitmq/"))
connection = pika.BlockingConnection(pika.URLParameters("amqp://guest:guest@localhost/"))
还尝试了
$ docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' rabbitmq
172.27.0.2
和
connection = pika.BlockingConnection(pika.URLParameters("amqp://guest:guest@172.27.0.2/")) #
还尝试了
credentials = pika.credentials.PlainCredentials(
username="guest",
password="guest"
)
parameters = pika.ConnectionParameters(
host=ip_address, # tried all above options
port=5672,
credentials=credentials,
heartbeat=10,
)
请注意,容器
car_parts_segmentor
能够看到容器rabbitmq
。两者都由docker-compose启动。
我的假设是这与uv_atp_network
两个容器都在其中有关,而我正在尝试从网络外部访问该网络内的坞站。
这真的是问题所在吗?
如果是,如何实现此目标?
面向未来-如何从pika获取更多信息性错误?
解决方案
正如我怀疑的那样,问题是名称rabbitmq
仅存在于网络uv_atp_network
中。
尝试连接到该网络的代码在其自身的容器中运行,而该容器不在网络中。
解决方案connectcurrent container到网络:
import socket
client = docker.from_env()
network_name = "uv_atp_network"
atp_container = client.containers.get(socket.gethostname())
client.networks.get(network_name).connect(container=atp_container.id)
此后,问题中的上述代码将正常工作,因为rabbitmq
可以解析。
connection = pika.BlockingConnection(pika.URLParameters("amqp://guest:guest@rabbitmq/"))
相关文章