Request Library and Docker Container: [Errno 111] Connection refused

How to fix

  • In your Dockerfile, ensure that you are running the Flask app by setting the FLASK_APP environment variable to the name of your app file ​(request.py in your case, default is app.py) and overriding the default port that Flask listens on:
ENV FLASK_APP=request.py
ENV FLASK_RUN_PORT=5003

CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]
  • Build your Docker container:
$ docker build -t request-example:latest .
  • Run your Docker image as a container, symmetrically exposing 5003 as the port for simplicity:
$ docker run -p 5003:5003 request-example:latest 
  • Test that the Flask app is now accessible on your local machine's localhost:
$ curl http://localhost:5003/
  • Or:
import requests as req

resp = req.get("http://localhost:5003/")

print(resp.text)

Suggestions

  • Create a requirements.txt that includes all your third-party libraries:
flask
requests
jsonify
  • Rewrite your Dockerfile to install whatever is in requirements.txt, rather than just the requests library:
FROM python:3.8

WORKDIR /request

COPY requirements.txt requirements.txt
COPY request.py request.py

RUN pip install -r requirements.txt

ENV FLASK_APP=request.py
ENV FLASK_RUN_PORT=5003

CMD [ "python", "-m" , "flask", "run", "--host=0.0.0.0"]