part-2 容器(container)
簡介
Docker架構有三個層面,從高到低如下:
- stack(棧)
- services(服務)
- containers(容器)
現在接觸的這些在容器這一層裡,類似于底層的基礎;服務的話就是在此基礎上實作了哪些功能/服務;更高層的棧則是定義了這些服務内在的一些互動
docker的優勢
以往開發一個東西,在本機開發後還要去伺服器上去部署,就涉及到各種環境的配置,各種依賴軟體的安裝,很麻煩;docker相當于提供了一個類集裝箱的服務,把這些東西都打包好,提供标準的服務,你把集裝箱搬到這個船上,那個碼頭上,他都可以放在那裡,提供開發好的服務;要把這些東西打包,當然就需要配置,配置檔案就稱之為 dockerfile;也就是說:dockerfile決定了容器中的環境,而這個環境是與系統環境隔離的。
docker示例
- 某檔案夾下建立一個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和app.py檔案,内容分别是
Flask
Redis
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)
- 編譯(build),
docker build -t friendlyhello .
- 運作app,
docker run -p 4000:80 friendlyhello
- 檢視
,可以看到friendlyhello這個imagedocker image ls
- 浏覽器通路 localhost:4000,可以看到我們用flask寫的這個app
- 可以使用背景模式啟動這個app,指令是
docker run -d -p 4000:80 friendlyhello
- 背景模式啟動的app可以使用
來關閉docker container stop container_id
- 檢視docker正在運作的容器,
, 和Linux的docker ps
一樣,也可以加上ps
的參數來檢視全部-a
分享docker 鏡像
git對應有github,docker對應有dockerhub;先注冊一個dockerhub賬号,然後就可以分享了;
-
登陸賬号docker login
-
來打标簽,類似于docker tag image
docker tag friendlyhello wang/get-started:part2
-
,來push鏡像docker push username/repository:tag
- 拉取然後運作鏡像
docker run -p 4000:80 username/repository:tag