【问题标题】:Django 'failed connection' between two containers两个容器之间的Django“连接失败”
【发布时间】:2021-10-29 14:31:32
【问题描述】:

我目前正在尝试在我的两个 docker 容器(运行 Gunicorn/Django 的请求容器和运行 kroki 的 api 容器)之间建立连接。

我查看了其他答案,但似乎对解决方案一无所知,因此希望能在正确的方向上有所启发。

Docker 撰写:

version: '3.8'

services:
  app:
    build:
      context: ./my_app
      dockerfile: Dockerfile.prod
    command: gunicorn my_app.wsgi:application --bind 0.0.0.0:8000 --access-logfile -
    volumes:
      - static_volume:/home/app/web/staticfiles
    expose:
      - 8000
    environment:
      - DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 kroki
    env_file:
      - ./.env.prod
    depends_on:
      - db
  db:
    image: postgres:13.0-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    env_file:
      - ./.env.prod.db
  nginx:
    build: ./nginx
    volumes:
      - static_volume:/home/app/web/staticfiles
    ports:
      - 1337:80
    depends_on:
      - app
  kroki:
    image: yuzutech/kroki
    ports:
      - 7331:8000

volumes:
  postgres_data:
  static_volume:

settings.py

ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ")

在 django 中请求代码

url = 'http://kroki:7331/bytefield/svg/' + base64_var
        try:
            response = requests.get(url)
            return response.text
        except ConnectionError as e:
            print("Connection to bytefield module, unavailable")
            return None

我可以通过浏览器成功访问这两个容器,但是启动两个容器之间的内部调用的代码会抛出

requests.exceptions.ConnectionError: HTTPConnectionPool(host='kroki', port=7331): Max retries exceeded with url: /bytefield/svg/<API_URL_HERE> (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f286f5ecaf0>: Failed to establish a new connection: [Errno 111] Connection refused'))

我已经尝试通过 localhost:7331 和 127.0.0.1:7331 访问该网址,但似乎都没有任何帮助

【问题讨论】:

    标签: django docker docker-compose


    【解决方案1】:

    当您访问同一 network 中的其他容器时,您不必使用 host 中的公开端口来访问它们,而是使用容器中的应用程序正在侦听的实际端口。

    我做了一个非常简单的例子,以便您了解您的问题:

    version: '3.8'
    
    services:
      app:
        image: busybox
        entrypoint: tail -f /dev/null
      kroki:
        image: yuzutech/kroki
        ports:
          - 7331:8000
    

    来自主机

    ❯ curl -s -o /dev/null -w "%{http_code}" localhost:7331
    
    200
    

    来自应用

    / # wget kroki:7331
    Connecting to kroki:7331 (172.18.0.3:7331)
    wget: can't connect to remote host (172.18.0.3): Connection refused
    / # wget kroki:8000
    Connecting to kroki:8000 (172.18.0.3:8000)
    saving to 'index.html'
    index.html           100% |************************************************************************| 51087  0:00:00 ETA
    'index.html' saved
    

    【讨论】:

    • 啊。救命稻草!这是一种享受。非常感谢这个例子来解释,现在这更有意义了。
    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 2018-12-22
    • 2020-06-29
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 2020-03-23
    • 2014-05-07
    相关资源
    最近更新 更多