繁体   English   中英

无法从 docker-compose 的另一个容器访问 api 的 docker 容器

[英]docker container of api not accessible from another container of docker-compose

我有一个带有烧瓶应用程序的 docker-compose 和一些用 python 编写的测试来测试 api。 api 工作正常,但带有测试的容器返回此错误: equests.exceptions.ConnectionError: HTTPConnectionPool(host='my_api', port=5000): Max retries exceeded with url: /Authorization (Caused by NewConnectionError('<urllib3 .connection.HTTPConnection 对象位于 0x7f02ff5abf10>:无法建立新连接:[Errno 111] 连接被拒绝'))。

这是我的 docker-compose.yml :

version: "3.9"

networks:
  app_subnet:
    external: true
    

services:
       api:
         image: my_api
         container_name: my_api
         networks:
              app_subnet :
                    ipv4_address: 172.16.0.10
         ports:
              - "5000:5000"
              #- target: 5000
               # published: 5000
               # protocol: tcp
               # mode: host
       
       authentication:
          image: authentication
          depends_on:
              - api
          container_name: authentication_test
          networks:
                    - app_subnet 
                        
          volumes:
              - /home/oussama/Downloads/projet2/:/home/


volumes:
  shared_volume:
       name: shared_volume
       driver: local
       driver_opts:
              type: 'none'
              o: 'bind'
              device: '/home/oussama/Downloads/projet2'

我正在运行的测试之一:

import os
import requests

# définition de l'adresse de l'API
api_address = 'my_api'
# port de l'API
api_port = 5000


r = requests.get(
    url='http://{address}:{port}/Authorization'.format(address=api_address, port=api_port),
    headers= {
        'Authorization': 'alice=wonderland'
        }
)

output = '''
============================
    Authentication test
============================

request done at "/Authorization"
| username="alice"
| password="wonderland"

expected result = 200
actual restult = {status_code}

==>  {test_status}

'''


# statut de la requête
status_code = r.status_code

# affichage des résultats
if status_code == 200:
    test_status = 'SUCCESS'
else:
    test_status = 'FAILURE'
print(output.format(status_code=status_code, test_status=test_status))

api在docker-compose之后工作,我在端口5000上使用curl命令得到了我想要的结果。我检查过,没有其他进程正在使用这个端口。 我试图将测试代码中的 api_adress 更改为我在 yml 文件中修复的 ipv4_address 或直接使用 api container_name 两次我都有相同的错误:无法建立新连接:[Errno 111] 连接被拒绝'

请问有什么想法吗?

您需要确保您的Flask应用程序正在侦听您在此处的docker-compose文件中列出的正确地址。

localhost不起作用,因为每个容器具有不同的网络命名空间,这意味着不同容器的主机不同。

在我的烧瓶应用程序中,我用以下内容结束它: if name == " main ": app.run(host="0.0.0.0", port=5000)

在 dockerfile 我公开端口 5000 和如果我这样做: docker container run -p 5000:5000 -d my_api:latest

api 使用 localhost 响应我的 curl 命令

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM