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.

過去寫一個(gè)Python程序,需要在本機(jī)安裝Python運(yùn)行環(huán)境鳄炉,本機(jī)必須有序的安裝程序,才能按期望運(yùn)行程序。服務(wù)器也同理。
但是用Docker葵第,可以獲取一個(gè)Python運(yùn)行環(huán)境鏡像鳍咱,無需安裝,應(yīng)用代碼與鏡像一起構(gòu)建馅笙,以確保應(yīng)用的運(yùn)行環(huán)境及依賴一起運(yùn)行。

1 創(chuàng)建容器厉亏,新建一個(gè)工作目錄董习,加入3個(gè)文件
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 執(zhí)行以下命令爱只,等待下載及安裝

docker build -t friendlyhello .
控制臺(tái)輸出:
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 運(yùn)行image 將docker的80端口映射為宿主機(jī)的4000端口

docker run -p 4000:80 friendlyhello

瀏覽器請(qǐng)求localhost:4000


docker run -d -p 4000:80 friendlyhello 可以后臺(tái)運(yùn)行
docker container ls 查看容器ID
docker container stop 3ccdc83fda2d 使用容器ID結(jié)束

2 共享鏡像(操作方式類似于git)
2.1 首先再在https://cloud.docker.com網(wǎng)站注冊(cè)用戶
命令行使用用戶名密碼登錄

docker login 
控制臺(tái)輸出:
Login Succeeded

2.2 上傳鏡像
樣例 docker tag image username/repository:tag

docker tag friendlyhello gaojingyuan/testrepo:v1 

2.3 查看鏡像

docker image ls
控制臺(tái)輸出:
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 發(fā)布鏡像

docker push gaojingyuan/testrepo:v1
控制臺(tái)輸出:
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 執(zhí)行鏡像,如果本地沒有會(huì)從repository下載

docker run -p 4000:80 gaojingyuan/testrepo:v1
控制臺(tái)輸出:
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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末皿淋,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子恬试,更是在濱河造成了極大的恐慌窝趣,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,383評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件训柴,死亡現(xiàn)場(chǎng)離奇詭異哑舒,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)畦粮,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,522評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門散址,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人宣赔,你說我怎么就攤上這事预麸。” “怎么了儒将?”我有些...
    開封第一講書人閱讀 157,852評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵吏祸,是天一觀的道長。 經(jīng)常有香客問我钩蚊,道長贡翘,這世上最難降的妖魔是什么蹈矮? 我笑而不...
    開封第一講書人閱讀 56,621評(píng)論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮鸣驱,結(jié)果婚禮上泛鸟,老公的妹妹穿的比我還像新娘。我一直安慰自己踊东,他們只是感情好北滥,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,741評(píng)論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著闸翅,像睡著了一般再芋。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上坚冀,一...
    開封第一講書人閱讀 49,929評(píng)論 1 290
  • 那天济赎,我揣著相機(jī)與錄音,去河邊找鬼记某。 笑死司训,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的辙纬。 我是一名探鬼主播豁遭,決...
    沈念sama閱讀 39,076評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼叭喜,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼贺拣!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起捂蕴,我...
    開封第一講書人閱讀 37,803評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤譬涡,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后啥辨,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體涡匀,經(jīng)...
    沈念sama閱讀 44,265評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,582評(píng)論 2 327
  • 正文 我和宋清朗相戀三年溉知,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了陨瘩。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,716評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡级乍,死狀恐怖舌劳,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情玫荣,我是刑警寧澤甚淡,帶...
    沈念sama閱讀 34,395評(píng)論 4 333
  • 正文 年R本政府宣布,位于F島的核電站捅厂,受9級(jí)特大地震影響费坊,放射性物質(zhì)發(fā)生泄漏销凑。R本人自食惡果不足惜绘证,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,039評(píng)論 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望贿堰。 院中可真熱鬧,春花似錦啡彬、人聲如沸官边。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,798評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽注簿。三九已至,卻和暖如春跳仿,著一層夾襖步出監(jiān)牢的瞬間诡渴,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,027評(píng)論 1 266
  • 我被黑心中介騙來泰國打工菲语, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留妄辩,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,488評(píng)論 2 361
  • 正文 我出身青樓山上,卻偏偏與公主長得像眼耀,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子佩憾,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,612評(píng)論 2 350

推薦閱讀更多精彩內(nèi)容

  • 以下原文轉(zhuǎn)載于(https://docs.docker.com/docker-for-mac/)(想找中文版的最新...
    Veekend閱讀 7,551評(píng)論 0 17
  • 一哮伟、Docker 簡介 Docker 兩個(gè)主要部件:Docker: 開源的容器虛擬化平臺(tái)Docker Hub: 用...
    R_X閱讀 4,382評(píng)論 0 27
  • Docker — 云時(shí)代的程序分發(fā)方式 要說最近一年云計(jì)算業(yè)界有什么大事件?Google Compute Engi...
    ahohoho閱讀 15,514評(píng)論 15 147
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 171,838評(píng)論 25 707
  • 上周四晚上朋友琴焦急的打電話給我妄帘,在電話里她慌亂楞黄,懊惱,不知所措抡驼。經(jīng)過半個(gè)多小時(shí)的交談鬼廓,我明白了事情的大概。 琴有...
    落日秋葉閱讀 213評(píng)論 0 0