我有一个唯一依赖的应用程序是flask,它可以在docker外部正常运行并绑定到默认端口5000。这是完整的源代码:
from flask import Flask app = Flask(__name__) app.debug = True @app.route('/') def main(): return 'hi' if __name__ == '__main__': app.run()
问题是,当我在docker中部署此服务器时,服务器正在运行,但无法从容器外部访问。
以下是我的Dockerfile。该图像是装有烧瓶的ubuntu。焦油仅包含index.py上面列出的内容;
# Dockerfile FROM dreen/flask MAINTAINER dreen WORKDIR /srv # Get source RUN mkdir -p /srv COPY perfektimprezy.tar.gz /srv/perfektimprezy.tar.gz RUN tar x -f perfektimprezy.tar.gz RUN rm perfektimprezy.tar.gz # Run server EXPOSE 5000 CMD ["python", "index.py"]
这是我正在部署的步骤
$> sudo docker build -t perfektimprezy .
据我所知,上面的程序运行良好,图像中包含tar的内容/srv。现在,让我们在容器中启动服务器:
$> sudo docker run -i -p 5000:5000 -d perfektimprezy 1c50b67d45b1a4feade72276394811c8399b1b95692e0914ee72b103ff54c769
它真的在运行吗?
$> sudo docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 1c50b67d45b1 perfektimprezy:latest "python index.py" 5 seconds ago Up 5 seconds 0.0.0.0:5000->5000/tcp loving_wozniak $> sudo docker logs 1c50b67d45b1 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat
$> curl 127.0.0.1:5000 -v * Rebuilt URL to: 127.0.0.1:5000/ * Hostname was NOT found in DNS cache * Trying 127.0.0.1... * Connected to 127.0.0.1 (127.0.0.1) port 5000 (#0) > GET / HTTP/1.1 > User-Agent: curl/7.35.0 > Host: 127.0.0.1:5000 > Accept: */* > * Empty reply from server * Connection #0 to host 127.0.0.1 left intact curl: (52) Empty reply from server
空回复…但是该流程正在运行吗?
$> sudo docker top 1c50b67d45b1 UID PID PPID C STIME TTY TIME CMD root 2084 812 0 10:26 ? 00:00:00 python index.py root 2117 2084 0 10:26 ? 00:00:00 /usr/bin/python index.py
现在,让我们进入服务器并检查…
$> sudo docker exec -it 1c50b67d45b1 bash root@1c50b67d45b1:/srv# netstat -an Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 127.0.0.1:5000 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:47677 127.0.0.1:5000 TIME_WAIT Active UNIX domain sockets (servers and established) Proto RefCnt Flags Type State I-Node Path root@1c50b67d45b1:/srv# curl -I 127.0.0.1:5000 HTTP/1.0 200 OK Content-Type: text/html; charset=utf-8 Content-Length: 5447 Server: Werkzeug/0.10.4 Python/2.7.6 Date: Tue, 19 May 2015 12:18:14 GMT
问题是你只绑定到localhost接口,0.0.0.0如果要从外部访问容器,则应该绑定到。如果你更改:
0.0.0.0
if __name__ == '__main__': app.run()
至
if __name__ == '__main__': app.run(host='0.0.0.0')
它应该工作。