Answer a question

I'm brand new to Docker so I think there's something wrong in my setup.

Here's my app.py (reduced version):

import flask
from flask import request
from flask_cors import CORS, cross_origin

app = flask.Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

@app.route('/', methods=['GET'])
@cross_origin()
def index():
    return('Home')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

My Dockerfile:

FROM python:3

WORKDIR /app

ENV FLASK_APP=app.py

COPY ./requirements.txt .

RUN pip3 install -r requirements.txt

COPY . .

CMD ["python3", "app.py"]

I'm building the image with docker build -t flaskapi . and running with docker run --rm -it -p 80:5000 flaskapi which gives the following output:

* Serving Flask app "app" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://172.17.0.2:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!

Visiting localhost in the browser, everything works fine but when trying to vist http://172.17.0.2:5000/ or testing with Postman, I eventually get a timeout error. I feel like it's just a small mistake I've made somewhere but I can't quite see it. What can I do to fix this?

Answers

By default, Docker runs in a separate subnet that is not accessible by the outside world. To be able to access the service running inside the container, you will have to map one of your host's ports to the internal docker subnet.

In your run command, you map TCP 80 to TCP 5000 inside the docker network (the -p 80:5000 part). That's why your service is accessible when visiting http://localhost (80 is implied). In essence, any request to your port 80 will end up being served by the service running at http://172.17.0.2:5000/.

The 172.* ip is in Docker's subnet range. To communicate via that, with your current settings, you would have to be in another container that shares the same network as this one.

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐