pythondockerflask

Unable to load python flask API with a docker container


I'm trying to learn Docker containers with APIs. I have created a simple Hello World python REST API with flask:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == '__main__':
    app.run(host="127.0.0.1", debug=True, port=8080)

This works when I run the script and go to http://localhost:8080/

This is my Dockerfile:

# Use an official Python runtime as a parent image
FROM python:2.7-slim

# Set the working directory to /app
WORKDIR /hello_world

# Copy the current directory contents into the container at /app
ADD . /hello_world

# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt

EXPOSE 8080

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["python", "hello_world.py"]

requirements.txt:

Flask

My current directory contains Dockerfile, hello_world.py and requirements.txt.

I can successfully build the image with docker build -t hello_world ." Running it with docker run -p 8080:8080 -t hello_world gives me the following output:

 Serving Flask app "hello_world" (lazy loading)
 * Environment: production
 WARNING: Do not use the development server in a production environment.
 Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 985-433-141

When I try going to http://127.0.0.1:8080/ I get the "Can't reach this page" error. Do you know what I'm doing wrong? Thank you.


Solution

  • From my comment above:

    Try running the app on 0.0.0.0 and see if that helps. I know that would make a difference if you were working between two machines, but I'm not sure if it works on containers

    Posting as an answer because it worked and @mickmackusa asked. I check through some of the linked "related questions" and surprisingly none of them seemed like duplicates (but feel free to close this if one is found)