使用Dockerfile打包python

创建空白的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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1.Compose介绍 Docker Compose是一个用来定义和运行复杂应用的Docker工具。一个使用Doc...
    渝味阅读 7,427评论 0 2
  • 让博客Docker化,轻松上手Docker Docker是一个有趣的技术,在过去的两年已经从一个想法变成了全世界的...
    喵喵唔的老巢阅读 398评论 0 0
  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 6,319评论 0 10
  • 一、Docker创建镜像的方式有两种: 一种通过commit的方式:把做了一系列操作的容器关闭,然后利用docke...
    jie0112阅读 3,910评论 0 3
  • es6 字符串的新增属性。学习笔记此博文 字符串的遍历器的接口。 includes(),startsWith(),...
    strong9527阅读 360评论 0 0

友情链接更多精彩内容