如何解决容器化的 Python 应用程序无法连接到 RabbitMQ - pika
我一直在尝试将两个 hello-world python 应用程序(一个消费者和一个生产者)容器化,并让它们通过 RabbitMQ 相互通信。 在本地,当使用 localhost 作为 pika 连接的主机名时,一切正常。我可以在 5672 端口上发送和使用消息,在 15672 上我可以看到队列按预期工作。
当我尝试将这两个应用程序放入容器时出现问题。
消费者:
import pika,sys,os,socket
local_ip = socket.gethostbyname(socket.gethostname())
print(local_ip)
def main():
connection = pika.BlockingConnection(pika.ConnectionParameters(host=str(local_ip)))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch,method,properties,body):
print(" [x] Received %r" % body)
channel.basic_consume(queue='hello',on_message_callback=callback,auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('Interrupted')
try:
sys.exit(0)
except SystemExit:
os._exit(0)
如您所见,我编辑了主机参数以获取主机 IP,因为使用 localhost 我收到此错误:
Traceback (most recent call last):
File "/app/consumer.py",line 23,in <module>
main()
File "/app/consumer.py",line 8,in main
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
File "/usr/local/lib/python3.10/site-packages/pika/adapters/blocking_connection.py",line 360,in __init__
self._impl = self._create_connection(parameters,_impl_class)
File "/usr/local/lib/python3.10/site-packages/pika/adapters/blocking_connection.py",line 451,in _create_connection
raise self._reap_last_connection_workflow_error(error)
pika.exceptions.AMQPConnectionError
显然,这不是问题,因为我在传递主机 ip 时遇到了完全相同的错误。
我正在使用社区映像 rabbitmq:3-management 在 docker 中运行 RabbitMQ 服务器。
这是这个消费者文件的 Dockerfile:
FROM python:rc-alpine
RUN mkdir /app
WORKDIR /app
ADD . /app/
RUN pip install -r requirements.txt
EXPOSE 5672
CMD ["python","/app/consumer.py"]
我应该怎么做才能解决这个问题?我很确定这是一件微不足道的事,但我为此苦苦挣扎。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。