如何从 docker 容器向 localhost 发出请求?

Dmi*_*nov 4 python containers localhost request docker

我使用 docker-compose。我想向本地主机发出请求。但我收到这个错误:

requests.exceptions.ConnectionError: 
   HTTPConnectionPool(host='0.0.0.0', port=9011): Max retries exceeded 
with url: /api/user/registration (Caused by 
NewConnectionError('<urllib3.connection.HTTPConnection object at 
   0x7fac61209110>: Failed to establish a new connection: [Errno 111] 
   Connection refused'))
Run Code Online (Sandbox Code Playgroud)

我的代码:

import requests

response = requests.get('http://127.0.0.1:9011')
print(response.content)
Run Code Online (Sandbox Code Playgroud)

这是我的docker-compose.yml

version: '3.4'

services:
  web:
    build: .
    command: runserver
    env_file:
      - .env
    volumes:
      - 'static:/opt/app/static:rw'
    ports:
      - 8000:8000

volumes:
  static:
Run Code Online (Sandbox Code Playgroud)

Dmi*_*nov 6

我已经找到答案了。你应该添加network_mode: hostdocker-compose.yml

version: '3.4'

services:
  web:
    build: .
    command: runserver
    env_file:
      - .env
    volumes:
      - 'static:/opt/app/static:rw'
    ports:
      - 8000:8000
    network_mode: host  # Added this


volumes:
  static:
Run Code Online (Sandbox Code Playgroud)