Docker Compose:模拟外部服务

tee*_*kay 6 networking docker

我有以下情况:

我的应用程序由一个调用外部 API 的 Web 服务组成(例如,一些 SaaS 服务、ElasticSearch 等)。出于非单元测试的目的,我们希望控制外部服务,然后再注入故障。应用程序和“模拟”API 是 dockerized,现在我想用它docker-compose来启动所有容器。

因为应用程序有几个硬编码的地址(例如外部服务的主机名),我无法更改它们并且需要解决。

service容器使一个呼叫http://external-service.com/getsomestuff

我的想法是使用 docker 提供的一些功能将所有传出流量重新路由http://external-service.com/getsomestuff到模拟容器的外部,而无需更改 URL。

我的docker-compose.yaml样子:

version: '2'
services:
  service:
    build: ./service
    container_name: my-service1
    ports:
      - "5000:5000"
    command: /bin/sh -c "python3 app.py"

  api:
    build: ./api-mock
    container_name: my-api-mock
    ports:
      - "5001:5000"
    command: /bin/sh -c "python3 app.py"
Run Code Online (Sandbox Code Playgroud)

最后,我有一个驱动程序,它只执行以下操作:

curl -XGET localhost:5000/
curl -XPUT localhost:5001/configure?delay=10
curl -XGET localhost:5000/
Run Code Online (Sandbox Code Playgroud)

其中第二个curl只是将模拟中的延迟设置为 10 秒。

我考虑了几种选择:

  • 使用iptables-fu(需要修改 Dockerfiles 才能安装它)
  • 使用 docker 网络(这对我来说真的不清楚)

有什么简单的选择可以实现我想要的吗?

编辑

为了清楚起见,这里是service代码的相关部分:

import requests

@app.route('/')
def do_stuff():
    r = requests.get('http://external-service.com/getsomestuff')
    return process_api_response(r.text())
Run Code Online (Sandbox Code Playgroud)

lar*_*sks 1

我不完全清楚您要解决的问题是什么,但是如果您尝试external-service.com在容器内部将流量直接发送到“模拟”服务,我认为您应该能够使用extra_hosts指令来做到这一点在你的docker-compose.yml文件中。例如,如果我有这个:

version: "2"

services:
  example:
    image: myimage
    extra_hosts:
      - google.com:172.23.254.1
Run Code Online (Sandbox Code Playgroud)

这将导致/etc/hosts容器包含:

172.23.254.1    google.com
Run Code Online (Sandbox Code Playgroud)

尝试访问http://google.com将访问我的 Web 服务器(地址为 172.23.254.1)。