Wrong http header IP address for client when running FastAPI application in Docker container

  Kiến thức lập trình

I am running a FastAPI application (backend) which has some logic which depends on the ip address of the client which is connecting to the backend.

Here is some example code which shows how the client IP address is obtained by the FastAPI application.

@app.post('/api/example')
def send_order(data: SomeDataType, request: Request, response: Response):
    print(request.client.host) # ip address of client

This application is deployed behind an Nginx webserver, which is acting as a reverse proxy.

  • I setup Nginx to pass the ip address in the headers
location /api {
    proxy_pass http://localhost:5555/api;
    proxy_set_header        Host                    $host;
    proxy_set_header        X-Real-IP               $remote_addr;
    proxy_set_header        X-Forwarded-For         $proxy_add_x_forwarded_for;
    proxy_set_header        X-Forwarded-Proto       $scheme;
}
  • I configured Uvicorn to accept these headers
config = uvicorn.Config(
    'example:app',
    host='0.0.0.0',
    port=5555,
    log_level='info',
    proxy_headers=True,
)

server = uvicorn.Server(config)

So far, everything works.

However, the ip address information is lost as soon as I deploy the FastAPI application from within a Docker container.

I don’t fully understand why this is the case. If my knowledge of Docker networking is correct, then by default the network will be in bridge mode.

If I understand what I can see by running docker network list and docker network inspect project_name_default then it looks like the following things are happening:

  • network is bridge mode
  • it seems like bridge mode is essentially the same as a software router, meaning traffic is routed from one network address space to another
  • in this case, it seems that traffic is being routed from the host ip address to the docker container ip address

Quite why this causes the http headers to change the client ip address, I am not sure. This doesn’t seem to make much sense, so possibly something else is causing FastAPI to read the wrong ip, or I am otherwise misunderstanding what the issue is.

Can anyone offer any advice on how to diagnose this?

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT