簡體   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