如何在两个不同的docker容器中的两个django应用程序之间建立连接?

2024-01-26

我创建了两个应用程序“myapi”和“minombre”,其中“minombre”将向“myapi”发出一个简单的 GET 请求,并将它们放入两个单独的 docker 容器中。在运行“docker-compose up”后,容器运行,但api不传递数据。发出 GET 请求的“minombre”的views.py如下:

def index(request):
    response = requests.get('http://myapi')
    print(response)
    data = response.json()
    name = data['user']
    message = data['message']

    return HttpResponse('<h2> {} </h2> <br> <h5> {} </h5>'.format(name, message))

这是我用来运行容器的 docker-compose.yml。

version: '3'
services:
  myapi:
    build: ./myapi
    container_name: myapi
   
    ports:
      - "8001:8001"
    command: python manage.py runserver 0.0.0.0:8001
  
  minombre:
    build: ./minombre
    container_name: minombre
   
    ports:
      - "8000:8000"
    command: python manage.py runserver 0.0.0.0:8000

    depends_on:
      - myapi

这是例外:

Exception Type: ConnectionError
Exception Value:    
HTTPConnectionPool(host='myapi', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f69b902bbd0>: Failed to establish a new connection: [Errno 111] Connection refused'))

如果两个容器都部署在同一主机中,并且想要从“minombre”到“myapi”Django 应用程序进行 API 调用,那么您可以在“minombre”视图中使用下面的 URL,它应该可以工作。

response = requests.get('http://myapi:8001/')  # where myapi is the container name

EDIT

两个 Django 容器 minombre 和 myapi 分别运行在端口 8000 和 8001 上。

(venv) shakeel@my-workstation 20:54:44 ~/workspace $ sudo docker ps
CONTAINER ID        IMAGE                COMMAND                  CREATED             STATUS              PORTS                    NAMES
aefa0c5d4bc6        workspace_minombre   "python manage.py ru…"   15 minutes ago      Up 15 minutes       0.0.0.0:8000->8000/tcp   minombre
558e22e612f5        workspace_myapi      "python manage.py ru…"   15 minutes ago      Up 15 minutes       0.0.0.0:8001->8001/tcp   myapi
(venv) shakeel@my-workstation 20:54:48 ~/workspace $

当 DEBUG 为 True 并且 ALLOWED_HOSTS 为空时,将根据 ['localhost', '127.0.0.1', '[::1]'] 验证主机。 [来源][1]

(venv) shakeel@my-workstation 20:54:51 ~/workspace $ cat minombre/minombre/settings.py | grep "ALLOWED_HOST"
ALLOWED_HOSTS = []
(venv) shakeel@my-workstation 20:55:29 ~/workspace $ curl -I http://127.0.0.1:8000/polls/
HTTP/1.1 200 OK
Date: Tue, 05 Nov 2019 20:56:01 GMT
Server: WSGIServer/0.2 CPython/3.8.0
Content-Type: text/html; charset=utf-8
X-Frame-Options: SAMEORIGIN
Content-Length: 11

(venv) shakeel@my-workstation 20:56:01 ~/workspace $

现在我已将容器名称添加到允许的主机中

(venv) shakeel@my-workstation 21:00:42 ~/workspace $ cat myapi/myapi/settings.py |grep "ALLOWED_HOST"
ALLOWED_HOSTS = ['myapi', '127.0.0.1',]

我已向 API myapi:8001 添加了简单的 json 响应

(venv) shakeel@my-workstation 21:04:57 ~/workspace $ cat myapi/polls/views.py
from django.shortcuts import render
import json
from django.http import HttpResponse


def index(request):
    responseData = {
        'id': 4,
        'name': 'Test Response',
        'roles' : ['Admin','User']
    }

    return HttpResponse(json.dumps(responseData))

(venv) shakeel@my-workstation 21:05:02 ~/workspace $
(venv) shakeel@my-workstation 21:05:04 ~/workspace $

现在我们在 minombre:8000 的视图下调用 API myapi:8001

(venv) shakeel@my-workstation 21:05:04 ~/workspace $ cat minombre/polls/views.py
from django.shortcuts import render
import requests
from django.http import HttpResponse
from django.shortcuts import render


def index(request):
    response = requests.get('http://myapi:8001/polls/')
    data = response.json()
    return HttpResponse(data)
(venv) shakeel@my-workstation 21:05:14 ~/workspace $

现在,当您调用 minombre API 成功响应时。

(venv) shakeel@my-workstation 21:05:14 ~/workspace $ curl -I http://127.0.0.1:8000/polls/
HTTP/1.1 200 OK
Date: Tue, 05 Nov 2019 20:41:10 GMT
Server: WSGIServer/0.2 CPython/3.8.0
Content-Type: text/html; charset=utf-8
X-Frame-Options: SAMEORIGIN
Content-Length: 11

(venv) shakeel@my-workstation 21:05:14 ~/workspace $

但通过设置ALLOWED_HOSTS = ['myapi', '127.0.0.1',]我们无法从容器访问,但是您仍然可以从主机连接。

(venv) shakeel@my-workstation 21:06:19 ~/workspace $ curl -I http://127.0.0.1:8001/polls/
HTTP/1.1 200 OK
Date: Tue, 05 Nov 2019 21:06:31 GMT
Server: WSGIServer/0.2 CPython/3.8.0
Content-Type: text/html; charset=utf-8
X-Frame-Options: SAMEORIGIN
Content-Length: 62

(venv) shakeel@my-workstation 21:07:15 ~/workspace $ 
(venv) shakeel@my-workstation 21:08:15 ~/workspace $ cat myapi/myapi/settings.py |grep "ALLOWED_HOST"
ALLOWED_HOSTS = ['myapi', '127.0.0.1',]
(venv) shakeel@my-workstation 21:08:35 ~/workspace $ sudo docker exec -it minombre bash
root@aefa0c5d4bc6:/code# curl -I http://127.0.0.1:8001/polls/
curl: (7) Failed to connect to 127.0.0.1 port 8001: Connection refused
root@aefa0c5d4bc6:/code#
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在两个不同的docker容器中的两个django应用程序之间建立连接? 的相关文章

随机推荐