无法 运行 pytest\requests 测试 Docker 中的 Flask 应用程序
Can't run pytest\requests tests for Flask app inside Docker
我的设置 -
project/
app.py
test_hello.py
test/
Dockerfile
requirements.txt
app.py body 是
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 body 是
import requests
def test_hello():
session = requests.Session()
session.trust_env = False
s = session.get('http://localhost:5000/hello').text
assert s == 'hello bob'
Docker文件是
# 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
谁能告诉我哪里出了问题?非常感谢
当您处于 Docker 环境时,请尝试连接到 host.docker.internal
(而不是 127.0.0.1
)。根据 Docker 版本 (Windows/MacOS) 的不同,特殊 DNS 名称可能略有不同。
Here 是一个很好的答案,它解释了这个问题。
非常抱歉
问题出在 2 CMD 行的使用上
从docs-
There can only be one CMD instruction in a Dockerfile
我的设置 -
project/
app.py
test_hello.py
test/
Dockerfile
requirements.txt
app.py body 是
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 body 是
import requests
def test_hello():
session = requests.Session()
session.trust_env = False
s = session.get('http://localhost:5000/hello').text
assert s == 'hello bob'
Docker文件是
# 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
谁能告诉我哪里出了问题?非常感谢
当您处于 Docker 环境时,请尝试连接到 host.docker.internal
(而不是 127.0.0.1
)。根据 Docker 版本 (Windows/MacOS) 的不同,特殊 DNS 名称可能略有不同。
Here 是一个很好的答案,它解释了这个问题。
非常抱歉
问题出在 2 CMD 行的使用上
从docs-
There can only be one CMD instruction in a Dockerfile