【问题标题】:Can't run pytest\requests tests for Flask app inside Docker无法在 Docker 中为 Flask 应用程序运行 pytest\requests 测试
【发布时间】:2022-01-18 20:42:10
【问题描述】:

我的设置 -

project/
    app.py
    test_hello.py
    test/
    Dockerfile
    requirements.txt

app.py 正文是

from flask import Flask

app = Flask(__name__)


@app.route('/hello')
def privet():
    return 'hello bob'


if __name__ == '__main__':
    app.run(debug=True)

test_hello.py 正文是

import requests


def test_hello():
    session = requests.Session()
    session.trust_env = False
    s = session.get('http://localhost:5000/hello').text
    assert s == 'hello bob'

Dockerfile 是

# syntax=docker/dockerfile:1

FROM python:3.7-alpine
WORKDIR /code
ENV FLASK_APP=app
ENV FLASK_RUN_HOST=0.0.0.0
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
EXPOSE 5000
COPY . .
CMD ["flask", "run"]
CMD ["pytest"]

当我在我的机器上本地启动测试时 - 一切正常

但是当我在 Docker 容器上启动测试时(在构建映像和运行容器之后) - 我从请求中收到错误:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=5000): Max retries exceeded with url: /hello (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fbcacb07c90>: Failed to establish a new connection: [Errno 111] Connection refused'))

/usr/local/lib/python3.7/site-packages/requests/adapters.py:516: ConnectionError

谁能告诉我什么是错的?非常感谢

【问题讨论】:

    标签: python python-3.x docker python-requests pytest


    【解决方案1】:

    在 Docker 环境中尝试连接到host.docker.internal(而不是127.0.0.1)。根据 Docker 版本 (Windows/MacOS),特殊 DNS 名称可能略有不同。

    Here 是一个很好的答案,可以解释这个问题。

    【讨论】:

      【解决方案2】:

      对不起

      问题在于 2 个 CMD 行的使用

      来自docs -

      一个 Dockerfile 中只能有一条 CMD 指令

      【讨论】:

        猜你喜欢
        • 2019-02-08
        • 1970-01-01
        • 2021-09-25
        • 2022-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-12
        相关资源
        最近更新 更多