Search code examples
pythondockerflaskdocker-composedocker-swarm

Flask url_for doesn't compose correct url under docker/docker-compose


I have a Flask app running inside a Docker container running under a swarm. When I use url_for to create an external url for the API, it returns the docker service name rather than the absolute path.

Ex.

endpoint = url_for('api_v1.get_me_the_data', sn=123, 
                _external=True, _scheme="https")

returns something like https://app-primary:8000/api/v1/devices/123.

Other details:

  • running using Gunicorn behind an Nginx reverse proxy

I've tried playing with the SERVER_NAME, but no dice. Is there an easy way to fix this? Or should I write a wrapper function for url_for?


Solution

  • As you have the python application inside a container and also behind Nginx, then you might need to go with ProxyFix, it will do two things:

    • Getting the Client IP instead of nginx container IP by reading REMOTE_ADDR
    • Setting the Hostname by reading HTTP_HOST

    Next you need to make sure that nginx sends these Headers:

    proxy_set_header Host            $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;