[英]Can't run pytest\requests tests for Flask app inside Docker
我的設置 -
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
誰能告訴我出了什么問題? 太好了,謝謝
當您在 Docker 環境中時,嘗試連接到host.docker.internal
(而不是127.0.0.1
)。 特殊的 DNS 名稱可能會根據 Docker 版本(Windows/MacOS)略有不同。
這是一個很好的答案,可以解釋這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.