简体   繁体   中英

Unable to Access Local Host From Docker Container

Problem

I have two Docker containers:

  • a server ran with fastapi;uvicorn
  • a client sending a GET request to http://0.0.0.0

The server seems to work just fine as bashing curl -X GET http://0.0.0.0 works as expected. However, my docker client seems unable to get access.

After building the client container (files below), when running docker run -it --name app_client_container app_client:latest I receive the following error:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: Errno 111 Connection refused'))

Setup

My project looks like this

|- client.Dockerfile
|- client.py
|- client_req.txt
|- server.Dockerfile
|- server.py
|- server_req.txt

Client

# client.Dockerfile
FROM python:3.8

WORKDIR /srv
WORKDIR /srv
ADD client_req.txt /srv/client_req.txt
RUN pip install -r client_req.txt

ADD . /srv
CMD python /srv/client.py

# client.py
import json
import requests
import traceback

try:
    response = requests.get('http://0.0.0.0', timeout=5)
    print(json.dumps(response.json(), indent=4))
except Exception as e:
    print('Connection could not be established :(')
    print('Here is more information:')
    traceback.print_exc()

# client_req.txt
requests

Server

# server.Dockerfile
FROM python:3.8

WORKDIR /srv
ADD server_req.txt /srv/server_req.txt
RUN pip install -r server_req.txt

EXPOSE 80

ADD . /srv
CMD uvicorn server:app --host 0.0.0.0 --port 80 --reload

# server.py
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def read_root():
    return {"Hello": "World"}

# server_req.txt
fastapi
uvicorn

Try running the client with docker run ... --net=host ...

Although the server exposes :80 to the host, the host's network is not, by default, available to other containers; ie the host's :80 is not available inside other (including the client) containers.

Alternatively, you may:

  • reference the host via its DNS within the container;
  • create a docker network and bind both containers to it (thereby also using container names to reference)
  • or -- somewhat equally to the previous -- use Docker Compose.

You can also use default docker bridge network.

Set the IP address to: 172.17.0.1 (for mac it is docker.for.mac.host.internal)
This should work:

response = requests.get('http://172.17.0.1', timeout=5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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