无法在 Docker 中为 Flask 应用程序运行 pytest\requests 测试
Posted
技术标签:
【中文标题】无法在 Docker 中为 Flask 应用程序运行 pytest\\requests 测试【英文标题】: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
谁能告诉我什么是错的?非常感谢
【问题讨论】:
【参考方案1】:在 Docker 环境中尝试连接到host.docker.internal
(而不是127.0.0.1
)。根据 Docker 版本 (Windows/MacOS),特殊 DNS 名称可能略有不同。
Here 是一个很好的答案,可以解释这个问题。
【讨论】:
【参考方案2】:对不起
问题在于 2 个 CMD 行的使用
来自docs -
一个 Dockerfile 中只能有一条 CMD 指令
【讨论】:
以上是关于无法在 Docker 中为 Flask 应用程序运行 pytest\requests 测试的主要内容,如果未能解决你的问题,请参考以下文章
Docker Image与uWSGI / Gunicorn + Nginx for CentOS中的Flask应用程序
在 dockerized 环境中无法从 Flask 连接到 Kafka
如何在 docker 容器中设置 flask-socketio?
无法从 flask_migrate 导入 MigrateCommand
无法连接到 unix:///var/run/docker.sock 上的 Docker 守护程序。 docker 守护进程是不是正在运行?带有自托管运行器的 Gitlab Cloud CI/CD 错误