不同容器上烧瓶应用程序 运行 之间的连接

Connection between flask applications running on different containers

我在不同的容器上有 2 个烧瓶应用程序 运行。当我尝试从一个容器向另一个容器发出 API 请求时,出现以下错误:

HTTPConnectionPool(host='0.0.0.0', port=5001): Max retries exceeded with url: / (由NewConnectionError(': Failed to establish a new connection: [Errno 111] Connection拒绝'))

烧瓶应用程序 1:

app.route("/", methods=["GET"])
@cross_origin(supports_credentials=True)
def ads():
    r=requests.get('http://0.0.0.0:5001/',verify=False)
    return jsonify(r.text)

烧瓶应用程序 2:

app.route("/", methods=["GET"])
@cross_origin(supports_credentials=True)
def add2():
    return jsonify('Success!')

Docker app1 的文件:

FROM alpine:latest
RUN apk add --no-cache python3-dev \
    && pip3 install --upgrade pip
WORKDIR /
COPY . .
RUN pip3 --no-cache-dir install -r requirements.txt                                                                            
EXPOSE 5000
ENTRYPOINT  ["python3"]
CMD ["app.py","--host", "0.0.0.0"]

Docker app2 的文件:

FROM alpine:latest
RUN apk add --no-cache python3-dev \
    && pip3 install --upgrade pip
WORKDIR /
COPY . .
RUN pip3 --no-cache-dir install -r requirements.txt                                                                            
EXPOSE 5001
ENTRYPOINT  ["python3"]
CMD ["app.py","--host", "0.0.0.0"]

使用的docker命令是:

docker run -p 5000:5000 app1
docker run -p 5001:5001 app2

如何在不使用 docker-compose 的情况下解决此错误?

尝试使用您的 IPv4 地址。它会起作用

app.route("/", methods=["GET"])
@cross_origin(supports_credentials=True)
def ads():
    r=requests.get('192.168.10.7:5001/',verify=False)
    return jsonify(r.text)

你可以在你的机器上找到你的 ipv4, The IPv4 Address

或者您可以使用 ifconfig

从终端获取

您需要 create some non-default Docker network 并将两个容器附加到它。

停止并删除两个容器。 (这是一项非常常规的任务,尤其是对于这种更改;您应该确保没有数据实际存储在容器文件系统中,因为它会丢失。)然后创建网络并创建附加到它的两个容器,使用明确的名称:

docker network create app
docker run --net app --name app1 -p 5000:5000 app1
docker run --net app --name app2 -p 5001:5001 app2

现在这两个容器将能够使用它们的 --name 作为主机名访问其他容器。您可以调用 ,例如

requests.get('http://app2:5001/')

为了支持在 Docker 和非 Docker 世界中工作,我建议将此值设为可配置。您可以将其默认为 localhost 类型的地址,您可以在 Docker.

之外使用 运行 两个容器
app2_url = os.environ.get('APP2_URL', 'http://localhost:5001')
requests.get(app2_url)
docker run ... -e APP2_URL='http://app2:5001/' app1

(Docker 当您开始构建像这样的涉及 docker run 命令时,Compose 开始看起来很有吸引力;它主要只是相同内容的声明性 YAML 格式。虽然实际上并不需要.)