Deploying Flask app in docker. unable to connect t

2019-08-21 12:00发布

问题:

I've run docker file using python and flask. but i can't connect flask server in localhost. I've already confirmed that the code is working well with PyCham in Mac .

after checking the log, I think the flask server is working well in the container. but i can't connect in localhost


Python Code

# app.py
from flask import Flask

app = Flask('app')


@app.route('/')
def index():
    return "I'm from docker"


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



Dockerfile

FROM ubuntu:latest
MAINTAINER ian <ian@mysterico.com>

RUN apt-get update
RUN apt-get install python3 -y
RUN echo "python3 install SUCCESS #####"

RUN apt-get install python3-pip -y
RUN echo "pip3 install SUCCESS ######"

EXPOSE 5000

COPY requirements.txt /
COPY app.py /
WORKDIR /


RUN pip3 install -r requirements.txt

CMD python3 app.py

Some Docker logs

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
0691161cd0b5        flask:latest        "/bin/sh -c 'python3…"   2 minutes ago       Up 2 minutes        0.0.0.0:5000->5000/tcp   flask

$ docker logs 0691161cd0b5
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 280-257-458

$ docker exec -it 71305c45d05b bash
root@71305c45d05b:/# curl 127.0.0.1:5000 -v

Rebuilt URL to: 127.0.0.1:5000/
Trying 127.0.0.1...
TCP_NODELAY set
Connected to 127.0.0.1 (127.0.0.1) port 5000 (#0)
GET / HTTP/1.1
Host: 127.0.0.1:5000
User-Agent: curl/7.58.0
Accept: */*

HTTP 1.0, assume close after body
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 15
Server: Werkzeug/0.15.2 Python/3.6.7
Date: Mon, 15 Apr 2019 15:31:36 GMT

Closing connection 0
I'm from docker

I expect that it will return "I'm from docker" when i entered localhost:5000, but Chrome browser returned "Unable to connect"

What did I set wrong?

回答1:

I assume you are running docker on your localhost (and not on a VM)? Have you tried explicitly using port 5000 on flask?

app.run(host="0.0.0.0", port=int("5000"), debug=True)