首页 > 解决方案 > 使用环境变量从另一个 docker 容器访问本地 SQS 服务

问题描述

我有一个烧瓶应用程序,每当命中端点时,它都需要与 SQS 服务进行交互。我正在使用 docker 镜像在本地模拟 SQS 服务,该镜像sukumarporeddy/sqs:fp的基础镜像是https://github.com/vsouza/docker-SQS-local,并在配置中添加了另外两个队列。

我需要从作为app_service运行的另一个应用程序访问此服务。这两个服务使用docker-compose.yml文件运行,其中我提到了两个服务。

app_service

sqs_service

在构建应用程序映像时,我正在设置环境变量以将sqs_service作为QUEUE_ENDPOINT=http://sqs_service:9324. 但是当我尝试访问应用程序的sqs_service时,它​​说队列端点无效。

我正在使用boto3连接到本地sqs_service

boto3.client('sqs', endpoint_url=os.getenv("QUEUE_ENDPOINT"), region_name='default')

这是docker-compose.yml文件。

  app_service:
    container_name: app_container
    restart: always
    image: app
    build: 
      context: ./dsdp
      dockerfile: Dockerfile.app.local
    ports:
      - "5000:5000"
    env_file:
        - ./local_secrets.env
    command: flask run --host=0.0.0.0 --port 5000

  sqs_service:
    container_name: sqs_container
    image: sukumarporeddy/sqs:fp
    ports:
      - "9324:9324"

local_secrets.env:

QUEUE_ENDPOINT=https://sqs_service:9324
FEEDER_QUEUE_URL=https://sqs_service:9324/queue/feeder
PREDICTION_QUEUE_URL=https://sqs_service:9324/queue/prediction
AWS_ACCESS_KEY_ID=''
AWS_SECRET_ACCESS_KEY=''

尝试向本地运行的 SQS 服务发送消息时遇到的错误。

值错误

ValueError:无效的端点:https://sqs_service:9324

我在哪里犯错?

标签: dockerflaskdocker-composeboto3amazon-sqs

解决方案


不知何故,我无法使用环境变量中提到的服务名称来使用 SQS 队列。这就是我所做的。

从环境变量中获取服务名称,在 python 中使用套接字库获取服务的 IP 地址,并使用 IP 地址格式化和创建 QUEUE 端点 url。

import socket
queue_endpoint_service = os.getenv("QUEUE_ENDPOINT_SERVICE")
queue_endpoint_port = os.getenv("QUEUE_ENDPOINT_PORT")
feeder_queue = os.getenv("FEEDER_QUEUE")
prediction_queue = os.getenv("PREDICTION_QUEUE")
queue_endpoint_ip = socket.gethostbyname(queue_endpoint_service)
queue_endpoint = f"http://{queue_endpoint_ip}:{queue_endpoint_port}"
mc = boto3.client('sqs', endpoint_url=queue_endpoint, region_name='default')
feeder_queue_url = f"{queue_endpoint}/queue/{feeder_queue}"
prediction_queue_url = f"{queue_endpoint}/queue/{prediction_queue}"

我现在可以通过点击烧瓶应用程序中的端点来发送消息。

注意:还使用了Adiii提到的新 docker 镜像。不再使用旧图像。


推荐阅读