过去,如果您要开始编写Python应用程序,第一步就是把Python的运行环境安装到您的机器上,而且安装的环境还要和线上的一致,比较麻烦。
使用Docker,您可以从docker的官方registry或者其他仓库,获取一个可移植的Python运行环境镜像,无需安装。然后,你可以基于这个镜像开发你的应用程序,这样可以确保您的应用程序,依赖项和运行时都一起运行。
2.1、为了构建您自己的镜像,首先需要创建一个名称为Dockerfile的文件,用于定义创建镜像并运行container所需的步骤。 Dockerfile中的每条指令都会在镜像中创建一个层级。当您更改Dockerfile并重新build镜像时,只重建那些更改的层级。与其他虚拟化技术相比,这是使镜像轻量,小巧,快速的一个原因。
创建一个空目录,创建一个名为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
ADD . /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"]
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 = "cannot connect to Redis, counter disabled"
html = "Hello {name}!
" \
"Hostname: {hostname}
" \
"Visits: {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)
2.3 把我们的应用打包为镜像,要在DockerFile目录下执行。这会创建一个Docker镜像,我们将使用-t标记它,以使镜像有一个友好的名称。
docker build -t friendlyhello
运行应用程序,使用-p将机器的端口4000映射到容器暴露的端口80:
docker run -p 4000:80 friendlyhello
您也可以在shell中使用curl命令来查看相同的内容。
$ curl http://localhost:4000
Hello World!
Hostname: 8fc990912a14
Visits: cannot connect to Redis, counter disabled
按crtl+c结束应用
现在让我们在后台运行应用程序:
docker run -d -p 4000:80 friendlyhello
查看所有的container信息
$ docker container ls
CONTAINER ID IMAGE COMMAND CREATED
1fa4ab2cf395 friendlyhello "python app.py" 28 seconds ago
现在使用docker container stop来结束进程,使用CONTAINER ID,如下所示:
docker container stop 1fa4ab2cf395
4.1、我使用的是阿里云的docker registry,感觉应该会比较快。首先你要有一个阿里云的账号。然后登陆进去新建一个仓库,设置命名空间等信息。
4.2 登陆阿里云的docker registry,后续操作都需要登陆才可以执行。
sudo docker login --username=admin registry.cn-hangzhou.aliyuncs.com
4.3 为镜像打标,tag为可选的,如果没有,默认为latest
格式:
docker tag image_name registry_url/namespace/repository_name:[tag]
例如
docker tag friendlyhello registry.cn-hangzhou.aliyuncs.com/shuzhou/demo1:latest
查看本地的镜像列表
docker image ls
4.4 发布镜像
docker push registry.cn-hangzhou.aliyuncs.com/shuzhou/demo1:latest
4.5 现在你可以在任何一台机器上执行下面的命令,运行镜像
docker run -p 4000:80 registry.cn-hangzhou.aliyuncs.com/shuzhou/demo1:latest
4.6 拉取镜像
docker pull registry.cn-hangzhou.aliyuncs.com/shuzhou/demo1:latest