构buildPython Flask应用程序的Docker镜像

我正在尝试为Python Flask应用程序构build一个Docker镜像,但存在构build问题 – 所有文件都位于名为web的文件夹中 – 这是项目结构:

 web/ __init__.py app.py Dockerfile models.py requirements.txt 

app.py目前看起来像这样:

 from flask import Flask app = Flask(__name__) @app.route("/") def hello_world(): return "Hello World!" if __name__ == "__main__": app.run(debug=True,host='0.0.0.0') 

我已经从https://www.smartfile.com/blog/dockerizing-a-python-flask-application/ borrrowed Dockerfile

 FROM ubuntu:14.04 # Update OS RUN sed -i 's/# \(.*multiverse$\)/\1/g' /etc/apt/sources.list RUN apt-get update RUN apt-get -y upgrade # Install Python RUN apt-get install -y python-dev python-pip # Add requirements.txt ADD requirements.txt /webapp # Install wsgi Python web server RUN pip install uwsgi # Install app requirements RUN pip install -r requirements.txt # Create app directory ADD . /webapp # Set the default directory for our environment ENV HOME /webapp WORKDIR /webapp # Expose port 8000 for uwsgi EXPOSE 8000 ENTRYPOINT ["uwsgi", "--http", "0.0.0.0:8000", "--module", "app:app", "--processes", "1", "--threads", "8"] 

我正在尝试使用docker build --no-cache --rm -t flask-app来构buildDocker镜像,但它以一个错误信息结束:

 Successfully installed uwsgi Cleaning up... ---> 9bbc004212a3 Removing intermediate container 70ed8f07c408 Step 8/13 : RUN pip install -r requirements.txt ---> Running in f5e2eb59ffd1 Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' Storing debug log for failure in /root/.pip/pip.log The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 

我认为你的Dockerfile的一个非常小的变化可以解决这个问题:

 FROM ubuntu:14.04 # Update OS RUN sed -i 's/# \(.*multiverse$\)/\1/g' /etc/apt/sources.list RUN apt-get update RUN apt-get -y upgrade # Install Python RUN apt-get install -y python-dev python-pip # Add requirements.txt # Create app directory ADD . /webapp # Install wsgi Python web server RUN pip install uwsgi # Install app requirements # Full path to requirements RUN pip install -r /webapp/requirements.txt # Set the default directory for our environment ENV HOME /webapp WORKDIR /webapp # Expose port 8000 for uwsgi EXPOSE 8000 ENTRYPOINT ["uwsgi", "--http", "0.0.0.0:8000", "--module", "app:app", "--processes", "1", "--threads", "8"] 

我只是添加了requirements.txt的完整path,这可以通过几种不同的方式来完成,比如复制整个目录文件夹然后构build它。

在添加需求之前,我replace了Dockerfile的最初行

 FROM ubuntu:latest RUN apt-get update -y RUN apt-get install -y python-pip python-dev build-essential 

并成功地build立了图像。

 $ docker images REPOSITORY TAG IMAGE ID CREATED SIZE flask-app latest 32b81efb5719 2 minutes ago 644.9 MB ubuntu latest 104bec311bcd 5 weeks ago 129 MB $ $ docker run -d flask-app CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 73ae8baa93c2 flask-app "uwsgi --http 0.0.0.0" 6 seconds ago Up 5 seconds 8000/tcp lucid_heyrovsky $ $ docker inspect --format '{{ .NetworkSettings.IPAddress }}' 73ae8baa93c2 172.17.0.2 

所以当我试图指向URL http://172.17.0.2:8000/我什么也没有得到。