體驗新的開發環境
在以前,如果你想要進行Python開發,那么你第一件事情就是必須現在自己的電腦上面安裝Python運行時和類庫。
但是,這樣導致了一種情況,那就是為了期望應用運行正常必須跟你開發電腦環境一樣,服務器部署運行也是這樣的情況。
使用了Docker,你能夠僅抓取一個便攜式的作為鏡像的Python運行時,而無需安裝。這樣,你構建出來的東西包含了基礎的Python鏡像和你的應用代碼,保證了你的應用和它的依賴還有運行時都能夠作為整體來傳輸和使用。其實,你狗構建出來的東西還是鏡像,是通過一個叫做Dockerfile來定義的。
使用Dockerfile定義一個容器
Dockerfile能夠定義容器內部的環境如何運行。為了要訪問資源,像網絡接口和硬盤驅動在容器內部都是虛擬化的,與主機系統的其他部分都是隔離的,你不得不映射端口到外部,確定具體的文件交互格式。不管怎么樣,你使用Dockerfile
把你的應用定義成鏡像,就能夠做到無論在什么樣的環境下,都能夠運行地特別一致。
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"]
里面使用了
----------------------------------------app.py
andrequirements.txt兩個文件,接着創建
2 應用本身
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)
--------------------------------------------------
現在來分析,【pip install -r requirements.txt】這個命令安裝了Python版本的 Flask 和Redis,打印了環境變量 NAME,同時輸出了調用
socket.gethostname()結果。最后,因為Redis沒有運行(我們只是安裝了Python類庫,並沒有安裝服務器啊),結果可惜而知當用到時就會報錯。
3 構建應用
我們准備構建(就是打包),確保你是在目錄中

現在運行狗i按命令,使用 -t 參數來指定一個友好的名字
docker build -t friendlyhello .
看清楚了最后有一個空格和點,否則就會出錯,正確結果是這樣滴

網速慢,真煩人。
生成的鏡像去了哪里?在我們電腦的本地鏡像中心
運行你的應用
使用-p參數來映射宿主的端口到容器內的端口
docker run -p 4000:80 friendlyhello
結果

訪問本機瀏覽器 http://localhost:4000/
提示出錯了,不過這是在預期內。
使用 -d參數讓它在后台運行
docker run -d -p 4000:80 friendlyhello
查看運行

停止下來
docker stop 2c209c0636f4
分享你的鏡像
先去官網注冊一個賬號。
連接 Docker login
標記你的鏡像
命令
docker tag image username/repository:tag
例子
docker tag friendlyhello archimate/get-started:part1
結果

發布你的鏡像到注冊中心
之后,就可以從遠程來使用這個鏡像了
docker run -p 4000:80
archimate/get-started:part1。
到此,容器已經創建並發布成功,下一章介紹如果在服務中運行容器並擴展。