【问题标题】:Error while running a unit test of an API in docker container在 docker 容器中运行 API 的单元测试时出错
【发布时间】:2021-09-05 21:13:58
【问题描述】:

我正在开发 Docker 项目:我们有 api(快速 api),它在拉取图像然后运行容器后工作正常:

docker image pull toto/fastapi:1.0.0
docker container run -p 8000:8000 toto/fastapi:1.0.0

API 在主机的 8000 端口上可用 --> 我想使用 Dockerfile 在容器中对该 API 运行测试:

  1. 我创建了一个文件夹:其中包含 Dockerfile 和我的测试脚本:
toto_image_test1: ____
                    |______Dockerfile
                    |______script.py

备注:当我通过容器在本地运行我的测试脚本时:它工作正常并生成我正在寻找的输出。

  1. 我已经搭建了api测试相关的镜像:
docker image build -f Dockerfile . -t toto_image_test1:latest

然后,当我运行容器时,我遇到了一个问题: 这是我运行的容器:

docker container run -it -d toto_image_test1:latest

这是我的 Dockerfile 的内容:

FROM toto/fastapi:1.0.0
ARG address
ENV address = '0.0.0.0'
RUN echo $address
CMD ["Bash"]
ARG port
ENV port = 8000
RUN echo $port
CMD ["Bash"]
ADD script.py /home/ubuntu/toto_image_test1/script.py
COPY   script.py   /home/ubuntu/script.py
WORKDIR /home/ubuntu
CMD python3 /home/ubuntu/script.py
RUN python3 /home/ubuntu/script.py &

这是我脚本的第一部分:

import os
import requests
import json
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from time import sleep
api_port = os.environ.get('port')
print("api_port",api_port)
api_address = os.environ.get('address')
print("api_address",api_address)
pwd = os.environ.get('PWD')
print ( 'le path actuel ssssssssss',pwd)

# requête authentication
r = ''
while r == '':
    try:
        r = requests.get(url='http://0.0.0.0:8000/permissions'.format(address=api_address,` `port=api_port),params= {'username': 'XX','password': '****'})
        print("request rrrrrrrr",r)
        break
    except:
        print("Connection refused by the server..")
        print("Let me sleep for 5 seconds")
        print("ZZzzzz...")
        #print("URL is ",url)
        print("r is rrrrrrrrr ",r)
        time.sleep(5)
        print("Was a nice sleep, now let me continue...")
        continue

问题是我总是发现“r”总是空的:查询在容器内永远不会给出结果,但它在本地工作正常。

【问题讨论】:

    标签: python docker dockerfile fastapi


    【解决方案1】:

    欢迎来到SO ;) 首先,必须考虑到您不能在一个dockerfile 中多次调用CMD,因为已经提到here! 但是当我发现您将要运行一个 API 并通过 script.py 中的自定义场景对其进行测试时,我建议您先编写 RUN.sh 文件来运行您的服务和测试脚本,然后在最后调用它dockerfile 只有一个 CMD 指令。此外,当您从本地文件系统复制到映像时,最好使用COPY 而不是ADD。

    【讨论】:

    • 你好,谢谢你的回答,我已经更新了 Dockerfile 如下,但不幸的是我仍然有同样的问题:总是“r”是空的:FROM datascientest/fastapi:1.0.0 ARG address ENV address = '0.0.0.0' RUN echo $address ARG port ENV port = 8000 RUN echo $port COPY server.py /home/ubuntu/my_docker_image_test1/server.py COPY server.py /home/ubuntu/server.py WORKDIR /home/ubuntu CMD python3 /home/ubuntu/server.py RUN python3 /home/ubuntu/server.py &
    猜你喜欢
    • 2020-09-18
    • 2023-03-21
    • 1970-01-01
    • 2017-10-30
    • 2020-04-22
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 2018-09-21
    相关资源
    最近更新 更多