Dockerfile Demo

来源:互联网 发布:淘宝客设置通用计划 编辑:程序博客网 时间:2024/06/05 02:17

一,创建Dockerfile文件

# Use an official Python runtime as a parent imageFROM python:2.7-slim# Set the working directory to /appWORKDIR /app# Copy the current directory contents into the container at /appADD . /app# Install any needed packages specified in requirements.txtRUN pip install --trusted-host pypi.python.org -r requirements.txt# Make port 80 available to the world outside this containerEXPOSE 80# Define environment variableENV NAME World# Run app.py when the container launchesCMD ["python", "app.py"]

二,创建requirements.txt文件

FlaskRedis

三,创建app

app.pyfrom flask import Flaskfrom redis import Redis, RedisErrorimport osimport socket# Connect to Redisredis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2)app = Flask(__name__)@app.route("/")def hello():    try:        visits = redis.incr("counter")    except RedisError:        visits = "<i>cannot connect to Redis, counter disabled</i>"    html = "<h3>Hello {name}!</h3>" \           "<b>Hostname:</b> {hostname}<br/>" \           "<b>Visits:</b> {visits}"    return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname(), visits=visits)if __name__ == "__main__":    app.run(host='0.0.0.0', port=80)

以上三个文件位于同一目录下

四,Build the app

docker build -t friendlyhello .

通过以下命令查看

docker imagesREPOSITORY          TAG                 IMAGE ID            CREATED             SIZEfriendlyhello       latest              a10e529f7529        29 minutes ago      148MB

五,Run the app

docker run -p 4000:80 friendlyhello

六,验证
访问该机器的4000端口有如下结果

Hello World!Hostname: c0e1b5bbb181Visits: cannot connect to Redis, counter disabled