2.容器(Containers)

In the past, if you were to start writing a Python app, your first order of business was to install a Python runtime onto your machine. But, that creates a situation where the environment on your machine has to be just so in order for your app to run as expected; ditto for the server that runs your app.
With Docker, you can just grab a portable Python runtime as an image, no installation necessary. Then, your build can include the base Python image right alongside your app code, ensuring that your app, its dependencies, and the runtime, all travel together.

过去写一个Python程序,需要在本机安装Python运行环境,本机必须有序的安装程序,才能按期望运行程序。服务器也同理。
但是用Docker,可以获取一个Python运行环境镜像,无需安装,应用代码与镜像一起构建,以确保应用的运行环境及依赖一起运行。

1 创建容器,新建一个工作目录,加入3个文件
1.1 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 -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"]

如果有代理,需配置代理
# Set proxy server, replace host:port with values for your servers
ENV http_proxy host:port
ENV https_proxy host:port

1.2 requirements.txt

Flask
Redis

1.3 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)

1.4 执行以下命令,等待下载及安装

docker build -t friendlyhello .
控制台输出:
Sending build context to Docker daemon  11.78kB
Step 1/7 : FROM python:2.7-slim
2.7-slim: Pulling from library/python
d13d02fa248d: Pull complete
5875fae15e49: Pull complete
19a68c2b3f2d: Pull complete
6a420196b3d3: Pull complete
Digest: sha256:7a64f01690266b9c7b505c6fbe7153cd01c46de6798eeba58b1afa10a0efa228
Status: Downloaded newer image for python:2.7-slim
 ---> e9adbdab327d
Step 2/7 : WORKDIR /app
 ---> 6c8be0209b9b
Removing intermediate container 79518c2c25af
Step 3/7 : ADD . /app
 ---> f8ad81dc489b
Step 4/7 : RUN pip install -r requirements.txt
 ---> Running in 6fd799d76cec
Collecting Flask (from -r requirements.txt (line 1))
  Downloading Flask-0.12.2-py2.py3-none-any.whl (83kB)
Collecting Redis (from -r requirements.txt (line 2))
  Downloading redis-2.10.6-py2.py3-none-any.whl (64kB)
Collecting itsdangerous>=0.21 (from Flask->-r requirements.txt (line 1))
  Downloading itsdangerous-0.24.tar.gz (46kB)
Collecting Jinja2>=2.4 (from Flask->-r requirements.txt (line 1))
  Downloading Jinja2-2.9.6-py2.py3-none-any.whl (340kB)
Collecting Werkzeug>=0.7 (from Flask->-r requirements.txt (line 1))
  Downloading Werkzeug-0.12.2-py2.py3-none-any.whl (312kB)
Collecting click>=2.0 (from Flask->-r requirements.txt (line 1))
  Downloading click-6.7-py2.py3-none-any.whl (71kB)
Collecting MarkupSafe>=0.23 (from Jinja2>=2.4->Flask->-r requirements.txt (line 1))
  Downloading MarkupSafe-1.0.tar.gz
Building wheels for collected packages: itsdangerous, MarkupSafe
  Running setup.py bdist_wheel for itsdangerous: started
  Running setup.py bdist_wheel for itsdangerous: finished with status 'done'
  Stored in directory: /root/.cache/pip/wheels/fc/a8/66/24d655233c757e178d45dea2de22a04c6d92766abfb741129a
  Running setup.py bdist_wheel for MarkupSafe: started
  Running setup.py bdist_wheel for MarkupSafe: finished with status 'done'
  Stored in directory: /root/.cache/pip/wheels/88/a7/30/e39a54a87bcbe25308fa3ca64e8ddc75d9b3e5afa21ee32d57
Successfully built itsdangerous MarkupSafe
Installing collected packages: itsdangerous, MarkupSafe, Jinja2, Werkzeug, click, Flask, Redis
Successfully installed Flask-0.12.2 Jinja2-2.9.6 MarkupSafe-1.0 Redis-2.10.6 Werkzeug-0.12.2 click-6.7 itsdangerous-0.24
 ---> f51df28a7a50
Removing intermediate container 6fd799d76cec
Step 5/7 : EXPOSE 80
 ---> Running in 586b51058063
 ---> fbbd919d52c1
Removing intermediate container 586b51058063
Step 6/7 : ENV NAME World
 ---> Running in 20ba1eeb0e0b
 ---> d6a7bfb8a00a
Removing intermediate container 20ba1eeb0e0b
Step 7/7 : CMD python app.py
 ---> Running in 544d1d800091
 ---> b9da56efd7dc
Removing intermediate container 544d1d800091
Successfully built b9da56efd7dc
Successfully tagged friendlyhello:latest

1.5 查看镜像

docker image ls 或 docker images

1.6 运行image 将docker的80端口映射为宿主机的4000端口

docker run -p 4000:80 friendlyhello

浏览器请求localhost:4000


docker run -d -p 4000:80 friendlyhello 可以后台运行
docker container ls 查看容器ID
docker container stop 3ccdc83fda2d 使用容器ID结束

2 共享镜像(操作方式类似于git)
2.1 首先再在https://cloud.docker.com网站注册用户
命令行使用用户名密码登录

docker login 
控制台输出:
Login Succeeded

2.2 上传镜像
样例 docker tag image username/repository:tag

docker tag friendlyhello gaojingyuan/testrepo:v1 

2.3 查看镜像

docker image ls
控制台输出:
REPOSITORY             TAG                 IMAGE ID            CREATED             SIZE
gaojingyuan/testrepo   v1                  b9da56efd7dc        28 minutes ago      150MB
friendlyhello          latest              b9da56efd7dc        28 minutes ago      150MB
python                 2.7-slim            e9adbdab327d        6 days ago          138MB
hello-world            latest              05a3bd381fc2        6 weeks ago         1.84kB

2.4 发布镜像

docker push gaojingyuan/testrepo:v1
控制台输出:
The push refers to a repository [docker.io/gaojingyuan/testrepo]
03209beada39: Pushed
afa3600fb996: Pushed
f02dd5f87330: Pushed
267e945e8138: Mounted from library/python
227cf6fd7a76: Mounted from library/python
60ed3196351d: Mounted from library/python
29d71372a492: Mounted from library/python
v1: digest: sha256:32f4cbc9b9528c43b5b0f00ba1a3c4c4efb82f31b39c63fa809c695ff918972e size: 1788

2.5 执行镜像,如果本地没有会从repository下载

docker run -p 4000:80 gaojingyuan/testrepo:v1
控制台输出:
Unable to find image 'gaojingyuan/testrepo:v1' locally
part2: Pulling from gaojingyuan/testrepo:v1

备注:

docker build -t friendlyname .  # Create image using this directory's Dockerfile
docker run -p 4000:80 friendlyname  # Run "friendlyname" mapping port 4000 to 80
docker run -d -p 4000:80 friendlyname         # Same thing, but in detached mode
docker container ls                                # List all running containers
docker container ls -a             # List all containers, even those not running
docker container stop <hash>           # Gracefully stop the specified container
docker container kill <hash>         # Force shutdown of the specified container
docker container rm <hash>        # Remove specified container from this machine
docker container rm $(docker container ls -a -q)         # Remove all containers
docker image ls -a                             # List all images on this machine
docker image rm <image id>            # Remove specified image from this machine
docker image rm $(docker image ls -a -q)   # Remove all images from this machine
docker login             # Log in this CLI session using your Docker credentials
docker tag <image> username/repository:tag  # Tag <image> for upload to registry
docker push username/repository:tag            # Upload tagged image to registry
docker run username/repository:tag                   # Run image from a registry
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,732评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,496评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,264评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,807评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,806评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,675评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,029评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,683评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,704评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,666评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,773评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,413评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,016评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,204评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,083评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,503评论 2 343

推荐阅读更多精彩内容

  • 以下原文转载于(https://docs.docker.com/docker-for-mac/)(想找中文版的最新...
    Veekend阅读 7,543评论 0 17
  • 一、Docker 简介 Docker 两个主要部件:Docker: 开源的容器虚拟化平台Docker Hub: 用...
    R_X阅读 4,377评论 0 27
  • Docker — 云时代的程序分发方式 要说最近一年云计算业界有什么大事件?Google Compute Engi...
    ahohoho阅读 15,508评论 15 147
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,451评论 25 707
  • 上周四晚上朋友琴焦急的打电话给我,在电话里她慌乱,懊恼,不知所措。经过半个多小时的交谈,我明白了事情的大概。 琴有...
    落日秋叶阅读 209评论 0 0