1. 程式人生 > >系統學習Docker

系統學習Docker

一、Docker 簡介

Docker 兩個主要部件:

  • Docker: 開源的容器虛擬化平臺
  • Docker Hub: 用於分享、管理 Docker 容器的 Docker SaaS 平臺 – Docker Hub

Docker 使用客戶端-伺服器 (C/S) 架構模式。Docker 客戶端會與 Docker 守護程序進行通訊。Docker 守護程序會處理複雜繁重的任務,例如建立、執行、釋出你的 Docker 容器。Docker 客戶端和守護程序可以執行在同一個系統上,當然你也可以使用 Docker 客戶端去連線一個遠端的 Docker 守護程序。Docker 客戶端和守護程序之間通過 socket 或者 RESTful API 進行通訊。

1.1 Docker 守護程序

如上圖所示,Docker 守護程序執行在一臺主機上。使用者並不直接和守護程序進行互動,而是通過 Docker 客戶端間接和其通訊。

1.2 Docker 客戶端

Docker 客戶端,實際上是 docker 的二進位制程式,是主要的使用者與 Docker 互動方式。它接收使用者指令並且與背後的 Docker 守護程序通訊,如此來回往復。

1.3 Docker 內部

要理解 Docker 內部構建,需要理解以下三種部件:

  • Docker 映象 - Docker images
  • Docker 倉庫 - Docker registeries
  • Docker 容器 - Docker containers

Docker 映象

Docker 映象是 Docker 容器執行時的只讀模板,每一個映象由一系列的層 (layers) 組成。Docker 使用 UnionFS 來將這些層聯合到單獨的映象中。UnionFS 允許獨立檔案系統中的檔案和資料夾(稱之為分支)被透明覆蓋,形成一個單獨連貫的檔案系統。正因為有了這些層的存在,Docker 是如此的輕量。當你改變了一個 Docker 映象,比如升級到某個程式到新的版本,一個新的層會被建立。因此,不用替換整個原先的映象或者重新建立(在使用虛擬機器的時候你可能會這麼做),只是一個新的層被新增或升級了。現在你不用重新發布整個映象,只需要升級,層使得分發 Docker 映象變得簡單和快速。

Docker 倉庫

Docker 倉庫用來儲存映象,可以理解為程式碼控制中的程式碼倉庫。同樣的,Docker 倉庫也有公有和私有的概念。公有的 Docker 倉庫名字是 Docker Hub。Docker Hub 提供了龐大的映象集合供使用。這些映象可以是自己建立,或者在別人的映象基礎上建立。Docker 倉庫是 Docker 的分發部分。

Docker 容器

Docker 容器和資料夾很類似,一個Docker容器包含了所有的某個應用執行所需要的環境。每一個 Docker 容器都是從 Docker 映象建立的。Docker 容器可以執行、開始、停止、移動和刪除。每一個 Docker 容器都是獨立和安全的應用平臺,Docker 容器是 Docker 的執行部分。

1.4 libcontainer

Docker 從 0.9 版本開始使用 libcontainer 替代 lxc,libcontainer 和 Linux 系統的互動圖如下:

1.5 名稱空間「Namespaces」

pid namespace

不同使用者的程序就是通過 pid namespace 隔離開的,且不同 namespace 中可以有相同 PID。具有以下特徵:

  • 每個 namespace 中的 pid 是有自己的 pid=1 的程序(類似 /sbin/init 程序)
  • 每個 namespace 中的程序只能影響自己的同一個 namespace 或子 namespace 中的程序
  • 因為 /proc 包含正在執行的程序,因此在 container 中的 pseudo-filesystem 的 /proc 目錄只能看到自己 namespace 中的程序
  • 因為 namespace 允許巢狀,父 namespace 可以影響子 namespace 的程序,所以子 namespace 的程序可以在父 namespace 中看到,但是具有不同的 pid

mnt namespace

類似 chroot,將一個程序放到一個特定的目錄執行。mnt namespace 允許不同 namespace 的程序看到的檔案結構不同,這樣每個 namespace 中的程序所看到的檔案目錄就被隔離開了。同 chroot 不同,每個 namespace 中的 container 在 /proc/mounts 的資訊只包含所在 namespace 的 mount point。

net namespace

網路隔離是通過 net namespace 實現的, 每個 net namespace 有獨立的 network devices, IP addresses, IP routing tables, /proc/net 目錄。這樣每個 container 的網路就能隔離開來。 docker 預設採用 veth 的方式將 container 中的虛擬網絡卡同 host 上的一個 docker bridge 連線在一起。

uts namespace

UTS (“UNIX Time-sharing System”) namespace 允許每個 container 擁有獨立的 hostname 和 domain name, 使其在網路上可以被視作一個獨立的節點而非 Host 上的一個程序。

ipc namespace

container 中程序互動還是採用 Linux 常見的程序間互動方法 (interprocess communication - IPC), 包括常見的訊號量、訊息佇列和共享記憶體。然而同 VM 不同,container 的程序間互動實際上還是 host 上具有相同 pid namespace 中的程序間互動,因此需要在 IPC 資源申請時加入 namespace 資訊 - 每個 IPC 資源有一個唯一的 32bit ID。

user namespace

每個 container 可以有不同的 user 和 group id, 也就是說可以以 container 內部的使用者在 container 內部執行程式而非 Host 上的使用者。

有了以上 6 種 namespace 從程序、網路、IPC、檔案系統、UTS 和使用者角度的隔離,一個 container 就可以對外展現出一個獨立計算機的能力,並且不同 container 從 OS 層面實現了隔離。 然而不同 namespace 之間資源還是相互競爭的,仍然需要類似 ulimit 來管理每個 container 所能使用的資源 - cgroup。

Reference

1.6 資源配額「cgroups」

cgroups 實現了對資源的配額和度量。 cgroups 的使用非常簡單,提供類似檔案的介面,在 /cgroup 目錄下新建一個資料夾即可新建一個 group,在此資料夾中新建 task 檔案,並將 pid 寫入該檔案,即可實現對該程序的資源控制。具體的資源配置選項可以在該資料夾中新建子 subsystem ,{子系統字首}.{資源項} 是典型的配置方法, 如 memory.usage_in_bytes 就定義了該 group 在 subsystem memory 中的一個記憶體限制選項。 另外,cgroups 中的 subsystem 可以隨意組合,一個 subsystem 可以在不同的 group 中,也可以一個 group 包含多個 subsystem - 也就是說一個 subsystem。

  • memory
    • 記憶體相關的限制
  • cpu
    • 在 cgroup 中,並不能像硬體虛擬化方案一樣能夠定義 CPU 能力,但是能夠定義 CPU 輪轉的優先順序,因此具有較高 CPU 優先順序的程序會更可能得到 CPU 運算。 通過將引數寫入 cpu.shares ,即可定義改 cgroup 的 CPU 優先順序 - 這裡是一個相對權重,而非絕對值
  • blkio
    • block IO 相關的統計和限制,byte/operation 統計和限制 (IOPS 等),讀寫速度限制等,但是這裡主要統計的都是同步 IO
  • devices
    • 裝置許可權限制

二、Docker 安裝

docker 的相關安裝方法這裡不作介紹,具體安裝參考 官檔

獲取當前 docker 版本

$ sudo docker version
Client version: 1.3.2
Client API version: 1.15
Go version (client): go1.3.3
Git commit (client): 39fa2fa/1.3.2
OS/Arch (client): linux/amd64
Server version: 1.3.2
Server API version: 1.15
Go version (server): go1.3.3
Git commit (server): 39fa2fa/1.3.2

三、Docker 基礎用法

Docker HUB : Docker映象首頁,包括官方映象和其它公開映象

因為國情的原因,國內下載 Docker HUB 官方的相關映象比較慢,可以使用 Daocloud 映象加速。

3.1 Search images

$ sudo docker search ubuntu

3.2 Pull images

$ sudo docker pull ubuntu # 獲取 ubuntu 官方映象
$ sudo docker images # 檢視當前映象列表

3.3 Running an interactive shell

$ sudo docker run -i -t ubuntu:14.04 /bin/bash
  • docker run - 執行一個容器
  • -t - 分配一個(偽)tty (link is external)
  • -i - 互動模式 (so we can interact with it)
  • ubuntu:14.04 - 使用 ubuntu 基礎映象 14.04
  • /bin/bash - 執行命令 bash shell

注: ubuntu 會有多個版本,通過指定 tag 來啟動特定的版本 [image]:[tag]

$ sudo docker ps # 檢視當前執行的容器, ps -a 列出當前系統所有的容器
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
6c9129e9df10        ubuntu:14.04        /bin/bash           6 minutes ago       Up 6 minutes                            cranky_babbage

3.4 相關快捷鍵

  • 退出:Ctrl-D or exit
  • detach:Ctrl-P + Ctrl-Q
  • attach: docker attach CONTAINER-ID

四、Docker 命令幫助

4.1 docker help

docker command

$ sudo docker   # docker 命令幫助

Commands: attach Attach to a running container # 當前 shell 下 attach 連線指定執行映象 build Build an image from a Dockerfile # 通過 Dockerfile 定製映象 commit Create a new image from a container’s changes # 提交當前容器為新的映象 cp Copy files/folders from the containers filesystem to the host path # 從容器中拷貝指定檔案或者目錄到宿主機中 create Create a new container # 建立一個新的容器,同 run,但不啟動容器 diff Inspect changes on a container’s filesystem # 檢視 docker 容器變化 events Get real time events from the server # 從 docker 服務獲取容器實時事件 exec Run a command in an existing container # 在已存在的容器上執行命令 export Stream the contents of a container as a tar archive # 匯出容器的內容流作為一個 tar 歸檔檔案[對應 import ] history Show the history of an image # 展示一個映象形成歷史 images List images # 列出系統當前映象 import Create a new filesystem image from the contents of a tarball # 從tar包中的內容建立一個新的檔案系統映像[對應 export] info Display system-wide information # 顯示系統相關資訊 inspect Return low-level information on a container # 檢視容器詳細資訊 kill Kill a running container # kill 指定 docker 容器 load Load an image from a tar archive # 從一個 tar 包中載入一個映象[對應 save] login Register or Login to the docker registry server # 註冊或者登陸一個 docker 源伺服器 logout Log out from a Docker registry server # 從當前 Docker registry 退出 logs Fetch the logs of a container # 輸出當前容器日誌資訊 port Lookup the public-facing port which is NAT-ed to PRIVATE_PORT # 檢視對映埠對應的容器內部源埠 pause Pause all processes within a container # 暫停容器 ps List containers # 列出容器列表 pull Pull an image or a repository from the docker registry server # 從docker映象源伺服器拉取指定映象或者庫映象 push Push an image or a repository to the docker registry server # 推送指定映象或者庫映象至docker源伺服器 restart Restart a running container # 重啟執行的容器 rm Remove one or more containers # 移除一個或者多個容器 rmi Remove one or more images # 移除一個或多個映象[無容器使用該映象才可刪除,否則需刪除相關容器才可繼續或 -f 強制刪除] run Run a command in a new container # 建立一個新的容器並執行一個命令 save Save an image to a tar archive # 儲存一個映象為一個 tar 包[對應 load] search Search for an image on the Docker Hub # 在 docker hub 中搜索映象 start Start a stopped containers # 啟動容器 stop Stop a running containers # 停止容器 tag Tag an image into a repository # 給源中映象打標籤 top Lookup the running processes of a container # 檢視容器中執行的程序資訊 unpause Unpause a paused container # 取消暫停容器 version Show the docker version information # 檢視 docker 版本號 wait Block until a container stops, then print its exit code # 擷取容器停止時的退出狀態值 Run ‘docker COMMAND --help’ for more information on a command.

docker option

Usage of docker:
  --api-enable-cors=false                Enable CORS headers in the remote API                      # 遠端 API 中開啟 CORS 頭
  -b, --bridge=""                        Attach containers to a pre-existing network bridge         # 橋接網路
                                           use 'none' to disable container networking
  --bip=""                               Use this CIDR notation address for the network bridge's IP, not compatible with -b
                                         # 和 -b 選項不相容,具體沒有測試過
  -d, --daemon=false                     Enable daemon mode                                         # daemon 模式
  -D, --debug=false                      Enable debug mode                                          # debug 模式
  --dns=[]                               Force docker to use specific DNS servers                   # 強制 docker 使用指定 dns 伺服器
  --dns-search=[]                        Force Docker to use specific DNS search domains            # 強制 docker 使用指定 dns 搜尋域
  -e, --exec-driver="native"             Force the docker runtime to use a specific exec driver     # 強制 docker 執行時使用指定執行驅動器
  --fixed-cidr=""                        IPv4 subnet for fixed IPs (ex: 10.20.0.0/16)
                                           this subnet must be nested in the bridge subnet (which is defined by -b or --bip)
  -G, --group="docker"                   Group to assign the unix socket specified by -H when running in daemon mode
                                           use '' (the empty string) to disable setting of a group
  -g, --graph="/var/lib/docker"          Path to use as the root of the docker runtime              # 容器執行的根目錄路徑
  -H, --host=[]                          The socket(s) to bind to in daemon mode                    # daemon 模式下 docker 指定繫結方式[tcp or 本地 socket]
                                           specified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd.
  --icc=true                             Enable inter-container communication                       # 跨容器通訊
  --insecure-registry=[]                 Enable insecure communication with specified registries (no certificate verification for HTTPS and enable HTTP fallback) (e.g., localhost:5000 or 10.20.0.0/16)
  --ip="0.0.0.0"                         Default IP address to use when binding container ports     # 指定監聽地址,預設所有 ip
  --ip-forward=true                      Enable net.ipv4.ip_forward                                 # 開啟轉發
  --ip-masq=true                         Enable IP masquerading for bridge's IP range
  --iptables=true                        Enable Docker's addition of iptables rules                 # 新增對應 iptables 規則
  --mtu=0                                Set the containers network MTU                             # 設定網路 mtu
                                           if no value is provided: default to the default route MTU or 1500 if no default route is available
  -p, --pidfile="/var/run/docker.pid"    Path to use for daemon PID file                            # 指定 pid 檔案位置
  --registry-mirror=[]                   Specify a preferred Docker registry mirror
  -s, --storage-driver=""                Force the docker runtime to use a specific storage driver  # 強制 docker 執行時使用指定儲存驅動
  --selinux-enabled=false                Enable selinux support                                     # 開啟 selinux 支援
  --storage-opt=[]                       Set storage driver options                                 # 設定儲存驅動選項
  --tls=false                            Use TLS; implied by tls-verify flags                       # 開啟 tls
  --tlscacert="/root/.docker/ca.pem"     Trust only remotes providing a certificate signed by the CA given here
  --tlscert="/root/.docker/cert.pem"     Path to TLS certificate file                               # tls 證書檔案位置
  --tlskey="/root/.docker/key.pem"       Path to TLS key file                                       # tls key 檔案位置
  --tlsverify=false                      Use TLS and verify the remote (daemon: verify client, client: verify daemon) # 使用 tls 並確認遠端控制主機
  -v, --version=false                    Print version information and quit                         # 輸出 docker 版本資訊
$ sudo docker search --help

Usage: docker search TERM

Search the Docker Hub for images # 從 Docker Hub 搜尋映象

–automated=false Only show automated builds –no-trunc=false Don’t truncate output -s, --stars=0 Only displays with at least xxx stars

示例:

$ sudo docker search -s 100 ubuntu
# 查詢 star 數至少為 100 的映象,找出只有官方映象 start 數超過 100,預設不加 s 選項找出所有相關 ubuntu 映象
NAME      DESCRIPTION                  STARS     OFFICIAL   AUTOMATED
ubuntu    Official Ubuntu base image   425       [OK]

4.3 docker info

$ sudo docker info
Containers: 1                       # 容器個數
Images: 22                          # 映象個數
Storage Driver: devicemapper        # 儲存驅動
 Pool Name: docker-8:17-3221225728-pool
 Pool Blocksize: 65.54 kB
 Data file: /data/docker/devicemapper/devicemapper/data
 Metadata file: /data/docker/devicemapper/devicemapper/metadata
 Data Space Used: 1.83 GB
 Data Space Total: 107.4 GB
 Metadata Space Used: 2.191 MB
 Metadata Space Total: 2.147 GB
 Library Version: 1.02.84-RHEL7 (2014-03-26)
Execution Driver: native-0.2        # 儲存驅動
Kernel Version: 3.10.0-123.el7.x86_64
Operating System: CentOS Linux 7 (Core)

4.4 docker pull && docker push

$ sudo docker pull --help           # pull 拉取映象

Usage: docker pull [OPTIONS] NAME[:TAG]

Pull an image or a repository from the registry

-a, --all-tags=false Download all tagged images in the repository

$ sudo docker push # push 推送指定映象

Usage: docker push NAME[:TAG]

Push an image or a repository to the registry

示例:

$ sudo docker pull ubuntu           # 下載官方 ubuntu docker 映象,預設下載所有 ubuntu 官方庫映象
$ sudo docker pull ubuntu:14.04     # 下載指定版本 ubuntu 官方映象
$ sudo docker push 192.168.0.100:5000/ubuntu
# 推送映象庫到私有源[可註冊 docker 官方賬戶,推送到官方自有賬戶]
$ sudo docker push 192.168.0.100:5000/ubuntu:14.04
# 推送指定映象到私有源

4.5 docker images

列出當前系統映象

$ sudo docker images --help

Usage: docker images [OPTIONS] [NAME]

List images

-a, --all=false Show all images (by default filter out the intermediate image layers)

-a 顯示當前系統的所有映象,包括過渡層映象,預設 docker images 顯示最終映象,不包括過渡層映象

-f, --filter=[] Provide filter values (i.e. ‘dangling=true’) –no-trunc=false Don’t truncate output -q, --quiet=false Only show numeric IDs

示例:

$ sudo docker images            # 顯示當前系統映象,不包括過渡層映象
$ sudo docker images -a         # 顯示當前系統所有映象,包括過渡層映象
$ sudo docker images ubuntu     # 顯示當前系統 docker ubuntu 庫中的所有映象
REPOSITORY                 TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ubuntu                     12.04               ebe4be4dd427        4 weeks ago         210.6 MB
ubuntu                     14.04               e54ca5efa2e9        4 weeks ago         276.5 MB
ubuntu                     14.04-ssh           6334d3ac099a        7 weeks ago         383.2 MB

4.6 docker rmi

刪除一個或者多個映象

$ sudo docker rmi --help

Usage: docker rmi IMAGE [IMAGE…]

Remove one or more images

-f, --force=false Force removal of the image # 強制移除映象不管是否有容器使用該映象 –no-prune=false Do not delete untagged parents # 不要刪除未標記的父映象

4.7 docker run

$ sudo docker run --help

Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG…]

Run a command in a new container

-a, --attach=[] Attach to stdin, stdout or stderr. -c, --cpu-shares=0 CPU shares (relative weight) # 設定 cpu 使用權重 –cap-add=[] Add Linux capabilities –cap-drop=[] Drop Linux capabilities –cidfile="" Write the container ID to the file # 把容器 id 寫入到指定檔案 –cpuset="" CPUs in which to allow execution (0-3, 0,1) # cpu 繫結 -d, --detach=false Detached mode: Run container in the background, print new container id # 後臺執行容器 –device=[] Add a host device to the container (e.g. --device=/dev/sdc:/dev/xvdc) –dns=[] Set custom dns servers # 設定 dns –dns-search=[] Set custom dns search domains # 設定 dns 域搜尋 -e, --env=[] Set environment variables # 定義環境變數 –entrypoint="" Overwrite the default entrypoint of the image # ? –env-file=[] Read in a line delimited file of ENV variables # 從指定檔案讀取變數值 –expose=[] Expose a port from the container without publishing it to your host # 指定對外提供服務埠 -h, --hostname="" Container host name # 設定容器主機名 -i, --interactive=false Keep stdin open even if not attached # 保持標準輸出開啟即使沒有 attached –link=[] Add link to another container (name:alias) # 新增連結到另外一個容器 –lxc-conf=[] (lxc exec-driver only) Add custom lxc options --lxc-conf=“lxc.cgroup.cpuset.cpus = 0,1” -m, --memory="" Memory limit (format: <number><optional unit>, where unit = b, k, m or g) # 記憶體限制 –name="" Assign a name to the container # 設定容器名 –net=“bridge” Set the Network mode for the container # 設定容器網路模式 ‘bridge’: creates a new network stack for the container on the docker bridge ‘none’: no networking for this container ‘container:<name|id>’: reuses another container network stack ‘host’: use the host network stack inside the container. Note: the host mode gives the container full access to local system services such as D-bus and is therefore considered insecure. -P, --publish-all=false Publish all exposed ports to the host interfaces # 自動對映容器對外提供服務的埠 -p, --publish=[] Publish a container’s port to the host # 指定埠對映 format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort (use ‘docker port’ to see the actual mapping) –privileged=false Give extended privileges to this container # 提供更多的許可權給容器 –restart="" Restart policy to apply when a container exits (no, on-failure[:max-retry], always) –rm=false Automatically remove the container when it exits (incompatible with -d) # 如果容器退出自動移除和 -d 選項衝突 –security-opt=[] Security Options –sig-proxy=true Proxify received signals to the process (even in non-tty mode). SIGCHLD is not proxied. -t, --tty=false Allocate a pseudo-tty # 分配偽終端 -u, --user="" Username or UID # 指定執行容器的使用者 uid 或者使用者名稱 -v, --volume=[] Bind mount a volume (e.g., from the host: -v /host:/container, from docker: -v /container) # 掛載卷 –volumes-from=[] Mount volumes from the specified container(s) # 從指定容器掛載卷 -w, --workdir="" Working directory inside the container # 指定容器工作目錄

示例:

$ sudo docker images ubuntu
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ubuntu              14.04               e54ca5efa2e9        4 weeks ago         276.5 MB
... ...
$ sudo docker run -t -i -c 100 -m 512MB -h test1 -d --name="docker_test1" ubuntu /bin/bash
# 建立一個 cpu 優先順序為 100,記憶體限制 512MB,主機名為 test1,名為 docker_test1 後臺執行 bash 的容器
a424ca613c9f2247cd3ede95adfbaf8d28400cbcb1d5f9b69a7b56f97b2b52e5
$ sudo docker ps
CONTAINER ID        IMAGE           COMMAND         CREATED             STATUS              PORTS       NAMES
a424ca613c9f        ubuntu:14.04    /bin/bash       6 seconds ago       Up 5 seconds                    docker_test1
$ sudo docker attach docker_test1
[email protected]:/# pwd
/
[email protected]:/# exit
exit

關於cpu優先順序:

By default all groups have 1024 shares. A group with 100 shares will get a ~10% portion of the CPU time - archlinux cgroups

4.8 docker start|stop|kill… …

  • docker start CONTAINER [CONTAINER…]
    • # 執行一個或多個停止的容器
  • docker stop CONTAINER [CONTAINER…]
    • # 停掉一個或多個執行的容器 -t 選項可指定超時時間
  • docker kill [OPTIONS] CONTAINER [CONTAINER…]
    • # 預設 kill 傳送 SIGKILL 訊號 -s 可以指定傳送 kill 訊號型別
  • docker restart [OPTIONS] CONTAINER [CONTAINER…]
    • # 重啟一個或多個執行的容器 -t 選項可指定超時時間
  • docker pause CONTAINER
    • # 暫停一個容器,方便 commit
  • docker unpause CONTAINER
    • # 繼續暫停的容器
  • docker rm [OPTIONS] CONTAINER [CONTAINER…]
    • # 移除一個或多個容器
    • -f, –force=false Force removal of running container
    • -l, –link=false Remove the specified link and not the underlying container
    • -v, –volumes=false Remove the volumes associated with the container
  • docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
    • # 提交指定容器為映象
    • -a, –author=”” Author (e.g., “John Hannibal Smith [email protected]”)
    • -m, –message=”” Commit message
    • -p, –pause=true Pause container during commit
      • # 預設 commit 是暫停狀態
  • docker inspect CONTAINER|IMAGE [CONTAINER|IMAGE…]
    • # 檢視容器或者映象的詳細資訊
  • docker logs CONTAINER
    • # 輸出指定容器日誌資訊
    • -f, –follow=false Follow log output
      • # 類似 tail -f
    • -t, –timestamps=false Show timestamps
    • –tail=”all” Output the specified number of lines at the end of logs (defaults to all logs)

4.9 Docker 1.3 新增特性和命令

Digital Signature Verification

Docker 1.3 版本將使用數字簽名自動驗證所有官方庫的來源和完整性,如果一個官方映象被篡改或者被破壞,目前 Docker 只會對這種情況發出警告而並不阻止容器的執行。

Inject new processes with docker exec

docker exec --help

Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG…]

Run a command in an existing container

-d, --detach=false Detached mode: run command in the background -i, --interactive=false Keep STDIN open even if not attached -t, --tty=false Allocate a pseudo-TTY

為了簡化除錯,可以使用 docker exec 命令通過 Docker API 和 CLI 在執行的容器上執行程式。

$ docker exec -it ubuntu_bash bash

上例將在容器 ubuntu_bash 中建立一個新的 Bash 會話。

Tune container lifecycles with docker create

我們可以通過 docker run <image name> 命令建立一個容器並執行其中的程式,因為有很多使用者要求建立容器的時候不啟動容器,所以 docker create 應運而生了。

$ docker create -t -i fedora bash
6d8af538ec541dd581ebc2a24153a28329acb5268abe5ef868c1f1a261221752

上例建立了一個可寫的容器層 (並且打印出容器 ID),但是並不執行它,可以使用以下命令執行該容器:

$ docker start -a -i 6d8af538ec5
bash-4.2#

Security Options

通過 --security-opt 選項,執行容器時使用者可自定義 SELinux 和 AppArmor 卷標和配置。

$ docker run --security-opt label:type:svirt_apache -i -t centos \ bash

上例只允許容器監聽在 Apache 埠,這個選項的好處是使用者不需要執行 docker 的時候指定 --privileged 選項,降低安全風險。

4.10 Docker 1.5 新特性

五、Docker 埠對映

# Find IP address of container with ID <container_id> 通過容器 id 獲取 ip
$ sudo docker inspect <container_id> | grep IPAddress | cut -d ’"’ -f 4

無論如何,這些 ip 是基於本地系統的並且容器的埠非本地主機是訪問不到的。此外,除了埠只能本地訪問外,對於容器的另外一個問題是這些 ip 在容器每次啟動的時候都會改變。

Docker 解決了容器的這兩個問題,並且給容器內部服務的訪問提供了一個簡單而可靠的方法。Docker 通過埠繫結主機系統的介面,允許非本地客戶端訪問容器內部執行的服務。為了簡便的使得容器間通訊,Docker 提供了這種連線機制。

5.1 自動對映埠

-P 使用時需要指定 --expose 選項,指定需要對外提供服務的埠

$ sudo docker run -t -P --expose 22 --name server  ubuntu:14.04

使用 docker run -P 自動繫結所有對外提供服務的容器埠,對映的埠將會從沒有使用的埠池中 (49000..49900) 自動選擇,你可以通過 docker psdocker inspect <container_id> 或者 docker port <container_id> <port> 確定具體的繫結資訊。

5.2 繫結埠到指定介面

基本語法

$ sudo docker run -p [([<host_interface>:[host_port]])|(<host_port>):]<container_port>[/udp] <image> <cmd>

預設不指定繫結 ip 則監聽所有網路介面。

繫結 TCP 埠

# Bind TCP port 8080 of the container to TCP port 80 on 127.0.0.1 of the host machine.
$ sudo docker run -p 127.0.0.1:80:8080 <image> <cmd>
# Bind TCP port 8080 of the container to a dynamically allocated TCP port on 127.0.0.1 of the host machine.
$ sudo docker run -p 127.0.0.1::8080 <image> <cmd>
# Bind TCP port 8080 of the container to TCP port 80 on all available interfaces of the host machine.
$ sudo docker run -p 80:8080 <image> <cmd>
# Bind TCP port 8080 of the container to a dynamically allocated TCP port on all available interfaces
$ sudo docker run -p 8080 <image> <cmd>

繫結 UDP 埠

# Bind UDP port 5353 of the container to UDP port 53 on 127.0.0.1 of the host machine.
$ sudo docker run -p 127.0.0.1:53:5353/udp <image> <cmd>

六、Docker 網路配置

Dokcer 通過使用 Linux 橋接提供容器之間的通訊,docker0 橋接介面的目的就是方便 Docker 管理。當 Docker daemon 啟動時需要做以下操作:

  • creates the docker0 bridge if not present
    • # 如果 docker0 不存在則建立
  • searches for an IP address range which doesn’t overlap with an existing route
    • # 搜尋一個與當前路由不衝突的 ip 段
  • picks an IP in the selected range
    • # 在確定的範圍中選擇 ip
  • assigns this IP to the docker0 bridge
    • # 繫結 ip 到 docker0

6.1 Docker 四種網路模式

docker run 建立 Docker 容器時,可以用 –net 選項指定容器的網路模式,Docker 有以下 4 種網路模式:

  • host 模式,使用 –net=host 指定。
  • container 模式,使用 –net=container:NAME_or_ID 指定。
  • none 模式,使用 –net=none 指定。
  • bridge 模式,使用 –net=bridge 指定,預設設定。

host 模式

如果啟動容器的時候使用 host 模式,那麼這個容器將不會獲得一個獨立的 Network Namespace,而是和宿主機共用一個 Network Namespace。容器將不會虛擬出自己的網絡卡,配置自己的 IP 等,而是使用宿主機的 IP 和埠。

例如,我們在 10.10.101.105/24 的機器上用 host 模式啟動一個含有 web 應用的 Docker 容器,監聽 tcp 80 埠。當我們在容器中執行任何類似 ifconfig 命令檢視網路環境時,看到的都是宿主機上的資訊。而外界訪問容器中的應用,則直接使用 10.10.101.105:80 即可,不用任何 NAT 轉換,就如直接跑在宿主機中一樣。但是,容器的其他方面,如檔案系統、程序列表等還是和宿主機隔離的。

container 模式

這個模式指定新建立的容器和已經存在的一個容器共享一個 Network Namespace,而不是和宿主機共享。新建立的容器不會建立自己的網絡卡,配置自己的 IP,而是和一個指定的容器共享 IP、埠範圍等。同樣,兩個容器除了網路方面,其他的如檔案系統、程序列表等還是隔離的。兩個容器的程序可以通過 lo 網絡卡裝置通訊。

none模式

這個模式和前兩個不同。在這種模式下,Docker 容器擁有自己的 Network Namespace,但是,並不為 Docker容器進行任何網路配置。也就是說,這個 Docker 容器沒有網絡卡、IP、路由等資訊。需要我們自己為 Docker 容器新增網絡卡、配置 IP 等。

bridge模式

bridge 模式是 Docker 預設的網路設定,此模式會為每一個容器分配 Network Namespace、設定 IP 等,並將一個主機上的 Docker 容器連線到一個虛擬網橋上。當 Docker server 啟動時,會在主機上建立一個名為 docker0 的虛擬網橋,此主機上啟動的 Docker 容器會連線到這個虛擬網橋上。虛擬網橋的工作方式和物理交換機類似,這樣主機上的所有容器就通過交換機連在了一個二層網路中。接下來就要為容器分配 IP 了,Docker 會從 RFC1918 所定義的私有 IP 網段中,選擇一個和宿主機不同的IP地址和子網分配給 docker0,連線到 docker0 的容器就從這個子網中選擇一個未佔用的 IP 使用。如一般 Docker 會使用 172.17.0.0/16 這個網段,並將 172.17.42.1/16 分配給 docker0 網橋(在主機上使用 ifconfig 命令是可以看到 docker0 的,可以認為它是網橋的管理介面,在宿主機上作為一塊虛擬網絡卡使用)

6.2 列出當前主機網橋

$ sudo brctl show  # brctl 工具依賴 bridge-utils 軟體包
bridge name bridge id STP enabled interfaces
docker0 8000.000000000000 no

6.3 檢視當前 docker0 ip

$ sudo ifconfig docker0
docker0 Link encap:Ethernet HWaddr xx:xx:xx:xx:xx:xx
inet addr:172.17.42.1 Bcast:0.0.0.0 Mask:255.255.0.0

在容器執行時,每個容器都會分配一個特定的虛擬機器口並橋接到 docker0。每個容器都會配置同 docker0 ip 相同網段的專用 ip 地址,docker0 的 IP 地址被用於所有容器的預設閘道器。

6.4 執行一個容器

$ sudo docker run -t -i -d ubuntu /bin/bash
52f811c5d3d69edddefc75aff5a4525fc8ba8bcfa1818132f9dc7d4f7c7e78b4
$ sudo brctl show
bridge name bridge id STP enabled interfaces
docker0 8000.fef213db5a66 no vethQCDY1N

以上, docker0 扮演著 52f811c5d3d6 container 這個容器的虛擬介面 vethQCDY1N interface 橋接的角色。

使用特定範圍的 IP

Docker 會嘗試尋找沒有被主機使用的 ip 段,儘管它適用於大多數情況下,但是它不是萬能的,有時候我們還是需要對 ip 進一步規劃。Docker 允許你管理 docker0 橋接或者通過 -b 選項自定義橋接網絡卡,需要安裝 bridge-utils 軟體包。

基本步驟如下:

  • ensure Docker is stopped
    • # 確保 docker 的程序是停止的
  • create your own bridge (bridge0 for example)
    • # 建立自定義網橋
  • assign a specific IP to this bridge
    • # 給網橋分配特定的 ip
  • start Docker with the -b=bridge0 parameter
    • # 以 -b 的方式指定網橋
# Stopping Docker and removing docker0

$ sudo service docker stop $ sudo ip link set dev docker0 down $ sudo brctl delbr docker0

Create our own bridge

$ sudo brctl addbr bridge0 $ sudo ip addr add 192.168.5.1/24 dev bridge0 $ sudo ip link set dev bridge0 up

Confirming that our bridge is up and running

$ ip addr show bridge0 4: bridge0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state UP group default link/ether 66:38:d0:0d:76:18 brd ff:ff:ff:ff:ff:ff inet 192.168.5.1/24 scope global bridge0 valid_lft forever preferred_lft forever

Tell Docker about it and restart (on Ubuntu)

$ echo ‘DOCKER_OPTS="-b=bridge0"’ >> /etc/default/docker $ sudo service docker start

6.5 不同主機間容器通訊

不同容器之間的通訊可以藉助於 pipework 這個工具:

$ git clone https://github.com/jpetazzo/pipework.git
$ sudo cp -rp pipework/pipework /usr/local/bin/

安裝相應依賴軟體

$ sudo apt-get install iputils-arping bridge-utils -y

橋接網路

橋接網路可以參考 日常問題處理 Tips 關於橋接的配置說明,這裡不再贅述。

# brctl show
bridge name     bridge id               STP enabled     interfaces
br0             8000.000c291412cd       no              eth0
docker0         8000.56847afe9799       no              vetheb48029

可以刪除 docker0,直接把 docker 的橋接指定為 br0。也可以保留使用預設的配置,這樣單主機容器之間的通訊可以通過 docker0,而跨主機不同容器之間通過 pipework 新建 docker 容器的網絡卡橋接到 br0,這樣跨主機容器之間就可以通訊了。

  • ubuntu
$ sudo service docker stop
$ sudo ip link set dev docker0 down
$ sudo brctl delbr docker0
$ echo 'DOCKER_OPTS="-b=br0"' >> /etc/default/docker
$ sudo service docker start
  • CentOS 7/RHEL 7
$ sudo systemctl stop docker
$ sudo ip link set dev docker0 down
$ sudo brctl delbr docker0
$ cat /etc/sysconfig/docker | grep 'OPTIONS='
OPTIONS=--selinux-enabled -b=br0 -H fd://
$ sudo systemctl start docker

pipework

不同容器之間的通訊可以藉助於 pipework 這個工具給 docker 容器新建虛擬網絡卡並繫結 IP 橋接到 br0

$ git clone https://github.com/jpetazzo/pipework.git
$ sudo cp -rp pipework/pipework /usr/local/bin/
$ pipework
Syntax:
pipework <hostinterface> [-i containerinterface] <guest> <ipaddr>/<subnet>[@default_gateway] [macaddr][@vlan]
pipework <hostinterface> [-i containerinterface] <guest> dhcp [macaddr][@vlan]
pipework --wait [-i containerinterface]

如果刪除了預設的 docker0 橋接,把 docker 預設橋接指定到了 br0,則最好在建立容器的時候加上 --net=none,防止自動分配的 IP 在區域網中有衝突。

$ sudo docker run --rm -ti --net=none ubuntu:14.04 /bin/bash
[email protected]:/#
$                  # Ctrl-P + Ctrl-Q 回到宿主機 shell,容器 detach 狀態
$ sudo docker  ps
CONTAINER ID    IMAGE          COMMAND       CREATED         STATUS          PORTS      NAMES
a46657528059    ubuntu:14.04   "/bin/bash"   4 minutes ago   Up 4 minutes               hungry_lalande
$ sudo pipework br0 -i eth0 a46657528059 192.168.115.10/[email protected]
# 預設不指定網絡卡裝置名,則預設新增為 eth1
# 另外 pipework 不能新增靜態路由,如果有需求則可以在 run 的時候加上 --privileged=true 許可權在容器中手動新增,
# 但這種安全性有缺陷,可以通過 ip netns 操作
$ sudo docker attach a46657528059
[email protected]:/# ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 86:b6:6b:e8:2e:4d
          inet addr:192.168.115.10  Bcast:0.0.0.0  Mask:255.255.255.0
          inet6 addr: fe80::84b6:6bff:fee8:2e4d/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:8 errors:0 dropped:0 overruns:0 frame:0
          TX packets:9 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:648 (648.0 B)  TX bytes:690 (690.0 B)

[email protected]:/# route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 0.0.0.0 192.168.115.2 0.0.0.0 UG 0 0 0 eth0 192.168.115.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0

使用 ip netns 新增靜態路由,避免建立容器使用 --privileged=true 選項造成一些不必要的安全問題:

$ docker inspect --format="{{ .State.Pid }}" a46657528059 # 獲取指定容器 pid
6350
$ sudo ln -s /proc/6350/ns/net /var/run/netns/6350
$ sudo ip netns exec 6350 ip route add 192.168.0.0/16 dev eth0 via 192.168.115.2
$ sudo ip netns exec 6350 ip route    # 新增成功
192.168.0.0/16 via 192.168.115.2 dev eth0
... ...

在其它宿主機進行相應的配置,新建容器並使用 pipework 新增虛擬網絡卡橋接到 br0,測試通訊情況即可。

另外,pipework 可以建立容器的 vlan 網路,這裡不作過多的介紹了,官方文件已經寫的很清楚了,可以檢視以下兩篇文章:

七、Dockerfile

Docker 可以通過 Dockerfile 的內容來自動構建映象。Dockerfile 是一個包含建立映象所有命令的文字檔案,通過 docker build 命令可以根據 Dockerfile 的內容構建映象,在介紹如何構建之前先介紹下 Dockerfile 的基本語法結構。

Dockerfile 有以下指令選項:

  • FROM
  • MAINTAINER
  • RUN
  • CMD
  • EXPOSE
  • ENV
  • ADD
  • COPY
  • ENTRYPOINT
  • VOLUME
  • USER
  • WORKDIR
  • ONBUILD

7.1 FROM

用法:

FROM <image>

或者

FROM <image>
  • FROM 指定構建映象的基礎源映象,如果本地沒有指定的映象,則會自動從 Docker 的公共庫 pull 映象下來。
  • FROM 必須是 Dockerfile 中非註釋行的第一個指令,即一個 Dockerfile 從 FROM 語句開始。
  • FROM 可以在一個 Dockerfile 中出現多次,如果有需求在一個 Dockerfile 中建立多個映象。
  • 如果 FROM 語句沒有指定映象標籤,則預設使用 latest 標籤。

7.2 MAINTAINER

用法:

MAINTAINER <name>

指定建立映象的使用者

RUN 有兩種使用方式

  • RUN (the command is run in a shell - /bin/sh -c - shell form)
  • RUN [“executable”, “param1”, “param2”] (exec form)

每條 RUN 指令將在當前映象基礎上執行指定命令,並提交為新的映象,後續的 RUN 都在之前 RUN 提交後的映象為基礎,映象是分層的,可以通過一個映象的任何一個歷史提交點來建立,類似原始碼的版本控制。

exec 方式會被解析為一個 JSON 陣列,所以必須使用雙引號而不是單引號。exec 方式不會呼叫一個命令 shell,所以也就不會繼承相應的變數,如:

RUN [ "echo", "$HOME" ]

這種方式是不會達到輸出 HOME 變數的,正確的方式應該是這樣的

RUN [ "sh", "-c", "echo", "$HOME" ]

RUN 產生的快取在下一次構建的時候是不會失效的,會被重用,可以使用 --no-cache 選項,即 docker build --no-cache,如此便不會快取。

7.3 CMD

CMD 有三種使用方式:

  • CMD [“executable”,”param1”,”param2”] (exec form, this is the preferred form, 優先選擇)
  • CMD [“param1”,”param2”] (as default parameters to ENTRYPOINT)
  • CMD command param1 param2 (shell form)

CMD 指定在 Dockerfile 中只能使用一次,如果有多個,則只有最後一個會生效。

CMD 的目的是為了在啟動容器時提供一個預設的命令執行選項。如果使用者啟動容器時指定了執行的命令,則會覆蓋掉 CMD 指定的命令。

CMD 會在啟動容器的時候執行,build 時不執行,而 RUN 只是在構建映象的時候執行,後續映象構建完成之後,啟動容器就與 RUN 無關了,這個初學者容易弄混這個概念,這裡簡單註解一下。

7.4 EXPOSE

EXPOSE <port> [<port>...]

告訴 Docker 服務端容器對外對映的本地埠,需要在 docker run 的時候使用 -p 或者 -P 選項生效。

7.5 ENV

ENV <key> <value>       # 只能設定一個變數
ENV <key>=<value> ...   # 允許一次設定多個變數

指定一個環節變數,會被後續 RUN 指令使用,並在容器執行時保留。

例子:

ENV myName="John Doe" myDog=Rex\ The\ Dog \
    myCat=fluffy

等同於

ENV myName John Doe
ENV myDog Rex The Dog
ENV myCat fluffy

7.6 ADD

ADD <src>... <dest>

ADD 複製本地主機檔案、目錄或者遠端檔案 URLS 從 <src> 並且新增到容器指定路徑中 <dest>。

<src> 支援通過 GO 的正則模糊匹配,具體規則可參見 Go filepath.Match

ADD hom* /mydir/        # adds all files starting with "hom"
ADD hom?.txt /mydir/    # ? is replaced with any single character
  • <dest> 路徑必須是絕對路徑,如果 <dest> 不存在,會自動建立對應目錄
  • <src> 路徑必須是 Dockerfile 所在路徑的相對路徑
  • <src> 如果是一個目錄,只會複製目錄下的內容,而目錄本身則不會被複制

7.7 COPY

COPY <src>... <dest>

COPY 複製新檔案或者目錄從 <src> 新增到容器指定路徑中 <dest>。用法同 ADD,唯一的不同是不能指定遠端檔案 URLS。

7.8 ENTRYPOINT

  • ENTRYPOINT [“executable”, “param1”, “param2”] (the preferred exec form,優先選擇)
  • ENTRYPOINT command param1 param2 (shell form)

配置容器啟動後執行的命令,並且不可被 docker run 提供的引數覆蓋,而 CMD 是可以被覆蓋的。如果需要覆蓋,則可以使用 docker run --entrypoint 選項。

每個 Dockerfile 中只能有一個 ENTRYPOINT,當指定多個時,只有最後一個生效。

Exec form ENTRYPOINT 例子

通過 ENTRYPOINT 使用 exec form 方式設定穩定的預設命令和選項,而使用 CMD 新增預設之外經常被改動的選項。

FROM ubuntu
ENTRYPOINT ["top", "-b"]
CMD ["-c"]

通過 Dockerfile 使用 ENTRYPOINT 展示前臺執行 Apache 服務

FROM debian:stable
RUN apt-get update && apt-get install -y --force-yes apache2
EXPOSE 80 443
VOLUME ["/var/www", "/var/log/apache2", "/etc/apache2"]
ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]

Shell form ENTRYPOINT 例子

這種方式會在 /bin/sh -c 中執行,會忽略任何 CMD 或者 docker run 命令列選項,為了確保 docker stop 能夠停止長時間執行 ENTRYPOINT 的容器,確保執行的時候使用 exec 選項。

FROM ubuntu
ENTRYPOINT exec top -b

如果在 ENTRYPOINT 忘記使用 exec 選項,則可以使用 CMD 補上:

FROM ubuntu
ENTRYPOINT top -b
CMD --ignored-param1 # --ignored-param2 ... --ignored-param3 ... 依此類推

7.9 VOLUME

VOLUME ["/data"]

建立一個可以從本地主機或其他容器掛載的掛載點,後續具體介紹。

7.10 USER

USER daemon

指定執行容器時的使用者名稱或 UID,後續的 RUNCMDENTRYPOINT 也會使用指定使用者。

7.11 WORKDIR

WORKDIR /path/to/workdir

為後續的 RUNCMDENTRYPOINT 指令配置工作目錄。可以使用多個 WORKDIR 指令,後續命令如果引數是相對路徑,則會基於之前命令指定的路徑。

WORKDIR /a
WORKDIR b
WORKDIR c
RUN pwd

最終路徑是 /a/b/c

WORKDIR 指令可以在 ENV 設定變數之後呼叫環境變數:

ENV DIRPATH /path
WORKDIR $DIRPATH/$DIRNAME

最終路徑則為 /path/$DIRNAME。

7.12 ONBUILD

ONBUILD [INSTRUCTION]

配置當所建立的映象作為其它新建立映象的基礎映象時,所執行的操作指令。

例如,Dockerfile 使用如下的內容建立了映象 image-A:

[...]
ONBUILD ADD . /app/src
ONBUILD RUN /usr/local/bin/python-build --dir /app/src
[...]

如果基於 image-A 建立新的映象時,新