一、问题

你有一个基于Python框架Flask(http://flask.pocoo.org)编写的web应用程序,该程序运行于Ubuntu上。你希望在容器中运行这个应用。

二、解决方案

这里我使用很简单的Hello world!应用例子作为说明,起Python代码如下

  1. #!/usr/bin/env python
  2. form flask import Flask
  3. app = Flask(__name__)
  4. @app.route('/hi')
  5. def hello_world():
  6. return 'Hello World!'
  7. if __name__=='__main__':
  8. app.run(host='0.0.0.0',port=5000)

为了让这个程序能跑起来,需要编写一个Dockerfile文件,在Docekrfile文件使用

  • RUN指令来安装运行该程序需要的软件依赖。
  • EXPOSE指令将程序监听的端口暴露给外部
  • ADD指令将应用程序复制到镜像内的文件系统上

这个应用程序的Dockerfile如下所示。

  1. FROM ubuntu:update_vim
  2. RUN apt-get update
  3. RUN apt-get install -y python
  4. RUN apt-get install -y python pip
  5. RUN apt-get clean all
  6. RUN pip install flask
  7. ADD hello.py /tmp/hello.py
  8. EXPOSE 5000
  9. CMD ["python","/tmp/hello.py"]

这里我们没有对Dockerfile进行语法优化,这个Dockerfile语句RUN命令执行了更新缓存仓库,安装了Python和Pip然后安装了Flask微框架
ADD命令将hello.py文件复制到镜像的/tmp/下。这个应用程序(hello.py)使用了5000端口,并将端口暴露给Docker主机。最后通过CMD命令执行python /tmp/hello.py
剩下的工作就是构建镜像了,如下所示:

  1. $ docker build .
  2. Sending build context to Docker daemon 3.072kB
  3. Step 1/8 : FROM ubuntu:update_vim
  4. ---> 2719f7931237
  5. Step 2/8 : RUN apt-get update
  6. ---> Using cache
  7. ---> 534f0bb9bef2
  8. Step 3/8 : RUN apt-get install -y python
  9. ---> Using cache
  10. ---> 3d0e5dfe624a
  11. Step 4/8 : RUN apt-get install -y python3-pip
  12. ---> Using cache
  13. ---> 6c65fc0eb7c0
  14. Step 5/8 : RUN pip3 install flask
  15. ---> Running in fe58fbf09a8e
  16. Collecting flask
  17. Downloading Flask-1.1.2-py2.py3-none-any.whl (94 kB)
  18. |████████████████████████████████| 94 kB 118 kB/s
  19. ERROR: Could not find a version that satisfies the requirement itsdangerous>=0.24 (from flask) (from versions: none)
  20. ERROR: No matching distribution found for itsdangerous>=0.24 (from flask)

出现报错!待解决