美文网首页Docker
使用Dockerfile打包python

使用Dockerfile打包python

作者: 范得郭 | 来源:发表于2018-10-25 10:31 被阅读0次

创建空白的dockerfile:

  • 创建一个名为的文件Dockerfile,将以下内容复制并粘贴到该文件中,然后保存。
# Use an official Python runtime as a parent image
FROM python:2.7-slim

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt

# Make port 80 available to the world outside this container
EXPOSE 80

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["python", "app.py"]
  • 将app.py和requirements.txt发在dockerfile的同一级目录下

requirements.txt内容如下:

Flask
Redis

app.py内容如下:

from flask import Flask
from redis import Redis, RedisError
import os
import socket

# Connect to Redis
redis = 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)
  • 进入到工作目录查看文件:
$ ls
Dockerfile      app.py          requirements.txt

现在运行build命令。创建一个Docker镜像(后面有个点)

docker build -t friendlyhello .
  • 查看build的镜像
$ docker image ls

REPOSITORY            TAG                 IMAGE ID
friendlyhello         latest              326387cea398

相关文章

网友评论

    本文标题:使用Dockerfile打包python

    本文链接:https://www.haomeiwen.com/subject/aerqtqtx.html