How can I access my Flask API within a docker container?

Issue

I have set up a Flask API to try and host my TensorFlow model online which I’m using for a mobile app – I have created a docker image with all of the correct imports and whenever I run the docker container the terminal shows this:

But when I visit any of these links, they time out – I believe I understand that this happens because the real URL’s are in the docker’s localhost, but I don’t have a solution and I don’t see how I could access this from any IP once I host the API on something like AWS.

So the help I need is: How can I access the API so that I can test it and make sure it works and further how would I go about deploying this to something serverless.

Sorry if this is basic, it’s my first time using docker. Any help would be greatly appreciated.

My DockerFile:

FROM python:3.9.0-stretch

# Maintainer info
LABEL maintainer="{my_email}"

# Make working directories
RUN  mkdir -p  /digit-api
WORKDIR  /digit-api

# Upgrade pip with no cache
RUN pip install --no-cache-dir -U pip

# Copy application requirements file to the created working directory
COPY requirements.txt .

# Install application dependencies from the requirements file
RUN pip install -r requirements.txt
RUN apt-get update
RUN apt-get install ffmpeg libsm6 libxext6  -y

# Copy every file in the source folder to the created working directory
COPY  . .

# Run the python application
CMD ["flask", "run", "-h", "0.0.0.0", "-p", "5000"]

I know the issue isn’t with the python file because I tested it on localhost without the docker image and it worked fine – but I need a way to get in online 24/7 which is why I’m using docker.

I know there are similar questions here but the only solution that they all seem to have is app.run(host=’0.0.0.0′) which I have in my python file and nothing has changed.

Edit: I have run docker run -d -p 5001:5001 nea-api (5000 is taken for some reason which I don’t quite understand either) and now the response is localhost didn’t send any data instead of timing out.

Solution

Your application is listening on port 5000. The second docker run -p port number must match this port. The two port numbers don’t need to match each other. So, to map port 5001 on the host to port 5000 in the container, you’d use

#             host port (your choice)
#                vvvv
docker run -d -p 5001:5000 nea-api
#                     ^^^^
#               container port (matches server process's port)

Answered By – David Maze

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published