Docker: 基礎知識筆記


一、概述

參考資料

1. 三要素

返回目錄

  • 鏡像(image)
  • 容器(container)是用鏡像創建的運行實例。
  • 倉庫(repository)是集中存放鏡像的地方。

安裝 Docker 請參考官方文檔
配置阿里雲鏡像加速器請參考阿里文檔
運行 hello world docker run hello-world

二、基本命令

1. 幫助命令

返回目錄

  • 查看版本 docker version
  • 查看信息 docker info
  • 查看幫助 docker --help

2. 鏡像命令

A)搜索鏡像

返回目錄

  1. 使用方式:docker search [選項] 鏡像
    中文 英文 說明
    選項 OPTIONS 命令參數選項
    鏡像 TERM 就是鏡像名,爲啥是 TERM 不清楚
  2. 選項:
      -f, --filter filter   過濾顯示
          --format string   使用 Go 模板格式化顯示輸出
          --limit int       最大顯示條數(默認 25)
          --no-trunc        不截斷輸出
    
    過濾格式:name=value
    名稱 值類型 說明
    stars int 鏡像獲得的星數
    is-automated boolean 是否是自動構建的鏡像
    is-official boolean 是否是官方鏡像
    Go 模版
    佔位符 說明
    .Name 鏡像名稱
    .Description 鏡像說明
    .StarCount 獲得的星數
    .IsOfficial 如果是官方鏡像,則顯示“OK”
    .IsAutomated 如果是自動構建的鏡像,則顯示“OK”
  3. 舉例:
    #只搜索自動構建的鏡像
    docker search --filter is-automated=true node 
    #只搜索星數大於30的鏡像
    docker search --filter stars=30 node
    #格式化顯示 鏡像名:星數
    docker search --format "table {{.Name}}: {{.StarCount}}" node
    #格式化顯示爲表格,鏡像名 是否自動構建 是否官方
    docker search --format "table {{.Name}}\t{{.IsAutomated}}\t{{.IsOfficial}}" node
    #只顯示5條數據
    docker search --limit 5 node
    #不隱藏超出範圍的信息
    docker search --no-trunc node
    

B)下載鏡像

返回目錄

  1. 使用方式:docker pull [選項] 鏡像[:標籤|@摘要]
    中文 英文 說明
    選項 OPTIONS 命令參數選項
    鏡像 NAME 鏡像名
    標籤 TAG 一般是版本號,最新是 latest
    摘要 DIGEST 辨別版本用的
    DIGEST:sha256:7acfc89fbe60…75b3bec2010
    可以在 hub.docker.com 查到
  2. 選項:
      -a, --all-tags                下載所有帶標籤的鏡像到倉庫
          --disable-content-trust   跳過鏡像驗證(默認 true)
      -q, --quiet                   禁止詳細輸出
    
  3. 舉例:
    docker pull node #下載 nodejs 鏡像(標籤默認爲最新版本)
    docker pull node:12.16.1 #下載版本爲 12.16.1 的 nodejs 鏡像
    docker pull ubuntu@sha256:45b23dee08af5e43a7fea6c4cf9c25ccf269ee113168c19722f87876677c5cb2
    

C)查看鏡像

返回目錄

  1. 使用方式:docker images [選項] [鏡像名[:標籤]]

    中文 英文 說明
    選項 OPTIONS 命令參數選項
    鏡像 REPOSITORY 就是鏡像名,對應結果的 REPOSITORY 標題
  2. 選項:

      -a, --all             顯示所有鏡像 (默認隱藏中間鏡像)
          --digests         顯示鏡像的摘要(digests)
      -f, --filter filter   過濾顯示
          --format string   使用 Go 模板格式化顯示輸出
          --no-trunc        不截斷輸出
      -q, --quiet           只顯示鏡像ID
    

    過濾格式:name=value

    名稱 值類型 說明
    dangling boolean 懸空
    label label=<key>
    label=<key>=<value>
    標題
    before <image-name>[:<tag>], <image id> 或 <image@digest> 給定 id 或引用之前創建的過濾器的鏡像
    since <image-name>[:<tag>], <image id> 或 <image@digest> 過濾自給定 id 或引用以來創建的鏡像
    reference 鏡像參考的模式 過濾參考與指定模式匹配的圖像

    Go 模版

    佔位符 說明
    .Name 鏡像名稱
    .Description 鏡像說明
    .StarCount 獲得的星數
    .IsOfficial 如果是官方鏡像,則顯示“OK”
    .IsAutomated 如果是自動構建的鏡像,則顯示“OK”
  3. 舉例:

    #顯示全部的鏡像
    docker images -a
    #顯示鏡像名包含 node 的鏡像
    docker images node
    

D)刪除鏡像

返回目錄

  1. 使用方式:docker rmi [選項] 鏡像 [鏡像...]
  2. 選項:
      -f, --force      強制刪除
          --no-prune   不要刪除未標記的父級
    
  3. 舉例:
    docker rmi -f $(docker images -q) #刪除所有的鏡像
    

3. 容器命令

A)運行新容器並執行命令【未完成】

返回目錄

  1. 使用方式:docker run [選項] 鏡像 [命令] [參數...]

  2. 選項:

          --add-host list                  Add a custom host-to-IP mapping (host:ip)
      -a, --attach list                    Attach to STDIN, STDOUT or STDERR
          --blkio-weight uint16            Block IO (relative weight), between 10 and 1000, or 0 to disable
                                           (default 0)
          --blkio-weight-device list       Block IO weight (relative device weight) (default [])
          --cap-add list                   添加 Linux 能力
          --cap-drop list                  去掉 Linux 能力
          --cgroup-parent string           Optional parent cgroup for the container
          --cidfile string                 Write the container ID to the file
          --cpu-count int                  CPU count (Windows only)
          --cpu-percent int                CPU percent (Windows only)
          --cpu-period int                 Limit CPU CFS (Completely Fair Scheduler) period
          --cpu-quota int                  Limit CPU CFS (Completely Fair Scheduler) quota
          --cpu-rt-period int              Limit CPU real-time period in microseconds
          --cpu-rt-runtime int             Limit CPU real-time runtime in microseconds
      -c, --cpu-shares int                 CPU shares (relative weight)
          --cpus decimal                   Number of CPUs
          --cpuset-cpus string             CPUs in which to allow execution (0-3, 0,1)
          --cpuset-mems string             MEMs in which to allow execution (0-3, 0,1)
      -d, --detach                         Run container in background and print container ID
          --detach-keys string             Override the key sequence for detaching a container
          --device list                    Add a host device to the container
          --device-cgroup-rule list        Add a rule to the cgroup allowed devices list
          --device-read-bps list           Limit read rate (bytes per second) from a device (default [])
          --device-read-iops list          Limit read rate (IO per second) from a device (default [])
          --device-write-bps list          Limit write rate (bytes per second) to a device (default [])
          --device-write-iops list         Limit write rate (IO per second) to a device (default [])
          --disable-content-trust          Skip image verification (default true)
          --dns list                       Set custom DNS servers
          --dns-option list                Set DNS options
          --dns-search list                Set custom DNS search domains
          --entrypoint string              Overwrite the default ENTRYPOINT of the image
      -e, --env list                       Set environment variables
          --env-file list                  Read in a file of environment variables
          --expose list                    Expose a port or a range of ports
          --group-add list                 Add additional groups to join
          --health-cmd string              Command to run to check health
          --health-interval duration       Time between running the check (ms|s|m|h) (default 0s)
          --health-retries int             Consecutive failures needed to report unhealthy
          --health-start-period duration   Start period for the container to initialize before starting
                                           health-retries countdown (ms|s|m|h) (default 0s)
          --health-timeout duration        Maximum time to allow one check to run (ms|s|m|h) (default 0s)
          --help                           顯示使用方法
      -h, --hostname string                容器的 host name
          --init                           Run an init inside the container that forwards signals and reaps
                                           processes
      -i, --interactive                    Keep STDIN open even if not attached
          --io-maxbandwidth bytes          Maximum IO bandwidth limit for the system drive (Windows only)
          --io-maxiops uint                Maximum IOps limit for the system drive (Windows only)
          --ip string                      IPv4 地址 (如:172.30.100.104)
          --ip6 string                     IPv6 地址 (如:2001:db8::33)
          --ipc string                     IPC mode to use
          --isolation string               容器隔離技術
          --kernel-memory bytes            內核內存限制
      -l, --label list                     在容器上設置元數據
          --label-file list                讀取以行分隔標籤的文件
          --link list                      添加鏈接到另一個容器
          --link-local-ip list             容器 IPv4/IPv6 連接到本地地址
          --log-driver string              容器的日誌設備
          --log-opt list                   日誌設備選項 
          --mac-address string             容器 MAC 地址 (如:92:d0:c6:0a:29:33)
      -m, --memory bytes                   內存限制
          --memory-reservation bytes       內存軟限制
          --memory-swap bytes              Swap 等於內存 + swap:'-1' 不限制 swap
          --memory-swappiness int          調整容器的內存交換(swappiness) (0 到 100) (默認 -1)
          --mount mount                    給容器裝載(mount)個文件系統
          --name string                    分配一個名字給容器
          --network string                 將容器連接到網絡 (默認 "default")
          --network-alias list             爲容器添加網絡範圍(network-scoped)的別名
          --no-healthcheck                 Disable any container-specified HEALTHCHECK
          --oom-kill-disable               Disable OOM Killer
          --oom-score-adj int              Tune host's OOM preferences (-1000 to 1000)
          --pid string                     PID namespace to use
          --pids-limit int                 調整容器 pids 限制 (設置 -1 爲不限制)
          --platform string                如果服務器支持多平臺,則設置平臺
          --privileged                     授予此容器擴展權限
      -p, --publish list                   將容器的端口發佈到主機
      -P, --publish-all                    將所有公開的端口發佈到隨機端口
          --read-only                      將容器的根文件系統裝載(mount)爲只讀
          --restart string                 當容器退出時,重啓要應用的策略 (默認 "no""always"爲退出即重啓)
          --rm                             當它退出時自動移除容器
          --runtime string                 用於此容器的運行時
          --security-opt list              安全選項
          --shm-size bytes                 /dev/shm 的大小
          --sig-proxy                      將接收到的信號代理到進程 (默認 true)
          --stop-signal string             用信號停止容器 (默認 "SIGTERM")
          --stop-timeout int               超時 (單位:秒) 停止容器
          --storage-opt list               容器的存儲設備選項
          --sysctl map                     Sysctl options (默認 map[])
          --tmpfs list                     裝載(mount)tmpfs 目錄
      -t, --tty                            分配一個 僞-TTY
          --ulimit ulimit                  Ulimit options (默認 [])
      -u, --user string                    用戶名 或 UID (格式: <name|uid>[:<group|gid>])
          --userns string                  User namespace to use
          --uts string                     UTS namespace to use
      -v, --volume list                    綁定 裝載(mount) 的數據卷(volume)
          --volume-driver string           容器的可選數據卷(volume)設備
          --volumes-from list              從指定容器裝載(mount)數據卷(volumes)
      -w, --workdir string                 容器內的工作目錄
    

    比較常用的參數

      --name="IMAGENAME" #新容器的名字
      -d #後臺運行容器,並返回容器 ID,並啓動守護式容器
      -i #以交互模式運行容器,通常與 -t 同時使用
      -t #爲容器重新分配一個僞輸入終端,通常與 -i 同時使用
      -P #(大寫)隨機端口映射
      -p #(小寫)指定端口映射 
      # 格式:ip:hostPort:containerPort|ip::containerPort|hostPort:containerPort|containerPort
    
  3. 舉例:

    #說明:運行守護容器,並每個兩秒打印 hello mylog 日誌
    docker run -d centos /bin/sh -c "while true;do echo hello mylog;sleep 2;done" 
    docker run -it 88ec626ba223
    docker run -it -p 8888:8080 tomcat
    docker run --restart=always #退出後重啓,開機啓動
    

B)更新容器配置

返回目錄

  1. 使用方式:docker update [選項] 容器 [容器...]
  2. 選項:
          --blkio-weight uint16        Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
          --cpu-period int             Limit CPU CFS (Completely Fair Scheduler) period
          --cpu-quota int              Limit CPU CFS (Completely Fair Scheduler) quota
          --cpu-rt-period int          Limit the CPU real-time period in microseconds
          --cpu-rt-runtime int         Limit the CPU real-time runtime in microseconds
      -c, --cpu-shares int             CPU shares (relative weight)
          --cpus decimal               Number of CPUs
          --cpuset-cpus string         CPUs in which to allow execution (0-3, 0,1)
          --cpuset-mems string         MEMs in which to allow execution (0-3, 0,1)
          --kernel-memory bytes        Kernel memory limit
      -m, --memory bytes               Memory limit
          --memory-reservation bytes   Memory soft limit
          --memory-swap bytes          Swap limit equal to memory plus swap: '-1' to enable unlimited swap
          --restart string             當容器退出時,重啓要應用的策略("always"爲退出即重啓)
    
  3. 舉例:
    docker update --restart=always 88ec626ba223 #更新配置,關閉重啓,開機啓動
    

C)退出容器

返回目錄

  1. 退出並關閉容器:exit(命令)
  2. 退出不關閉容器:ctrl+P+Q(快捷鍵)

D)查看容器

返回目錄

  1. 使用方式:docker ps [OPTIONS]
  2. 選項:
      -a, --all             顯示所有容器 (默認只顯示運行中的)
      -f, --filter filter   過濾顯示
          --format string   使用 Go 模板格式化顯示輸出
      -n, --last int        顯示最近創建的 n 個容器 (包含所有狀態) (默認 -1)
      -l, --latest          顯示最後創建的容器 (包含所有狀態)
          --no-trunc        不截斷輸出
      -q, --quiet           只顯示數字ID
      -s, --size            顯示文件總大小
    
  3. 舉例:
    docker ps -a
    

E)啓動容器

返回目錄

  1. 使用方式:docker start [選項] 容器 [容器...]
  2. 選項:
      -a, --attach                 Attach STDOUT/STDERR and forward signals
         --checkpoint string       從此檢查點還原
         --checkpoint-dir string   使用自定義檢查點存儲目錄
         --detach-keys string      重寫用於分離容器的鍵序列
     -i, --interactive             Attach container's STDIN
    

F)重啓容器

返回目錄

  1. 使用方式:docker restart [選項] 容器 [容器...]
  2. 選項:
      -t, --time int   在停止容器之前等待的秒數 (默認 10)
    

G)停止容器

返回目錄

  1. 使用方式:docker stop [選項] 容器 [容器...]
  2. 選項:
      -t, --time int   在停止容器之前等待的秒數 (默認 10)
    

H)強制停止容器

返回目錄

  1. 使用方式:docker kill [選項] 容器 [容器...]
  2. 選項:
      -s, --signal string   發送到容器的信號 (默認 "KILL")
    

I)刪除容器

返回目錄

  1. 使用方式:docker rm [選項] 容器 [容器...]
  2. 選項:
      -f, --force     強制刪除 (用 SIGKILL)
      -l, --link      刪除指定的鏈接
      -v, --volumes   刪除與容器關聯的卷
    
  3. 舉例:
    docker rm -f 88ec626ba223 #刪除單個
    docker rm -f 88ec626ba223 99ec626ba334 #刪除多個
    docker rm -f $(docker ps -a -q) #刪除全部
    docker ps -a -q | xargs docker rm #刪除全部
    

J)查看容器日誌

返回目錄

  1. 使用方式:docker logs [選項] 容器ID
  2. 選項:
          --details        顯示提供給日誌的額外詳細信息
      -f, --follow         跟蹤日誌輸出
          --since string   顯示時間戳後的日誌 (e.g. 2013-01-02T13:23:37) 或
                           相對時間戳 (e.g. 42m for 42 minutes)
          --tail string    從日誌結尾顯示的行數 (默認 "all")
      -t, --timestamps     顯示時間戳
          --until string   顯示時間戳之前的日誌(如 2013-01-02T13:23:37) 或 相對的(42m for 42 minutes)
    
  3. 舉例:
    docker logs -t -f --tail 3 88ec626ba223
    

K)查看容器內運行的進程

返回目錄
顯示容器的運行進程

  1. 使用方式:docker top 容器 [ps 選項]

L)查看容器內部細節

返回目錄

  1. 使用方式:docker inspect [選項] 容器名|容器ID [容器名|容器ID...]
  2. 選項:
      -f, --format string   使用 Go 模板格式化顯示輸出
      -s, --size            如果是容器類型,則顯示總文件大小
          --type string     返回指定類型的JSON
    
  3. 舉例:
    docker inspect 88ec626ba223
    
    進入正在運行的容器,用命令行進行交互

M)直接進入已運行容器,不啓動新進程

返回目錄

  1. 使用方式:docker attach [選項] 容器
  2. 選項:
      --detach-keys string   Override the key sequence for detaching a container
      --no-stdin             Do not attach STDIN
      --sig-proxy            Proxy all received signals to the process (默認 true)
    
  3. 舉例:
    docker attach  88ec626ba223
    

N)在容器中打開新的終端,可啓動新進程

返回目錄

  1. 使用:docker exec [選項] 容器 命令 [參數...]
  2. 選項:
      -d, --detach               Detached mode: run command in the background
          --detach-keys string   Override the key sequence for detaching a container
      -e, --env list             Set environment variables
      -i, --interactive          Keep STDIN open even if not attached
          --privileged           Give extended privileges to the command
      -t, --tty                  Allocate a pseudo-TTY
      -u, --user string          Username or UID (format: <name|uid>[:<group|gid>])
      -w, --workdir string       Working directory inside the container
    
  3. 舉例:
    #進入容器,執行完返回結果並退出容器(容器不停止)
    docker exec -it 88ec626ba223 ls -a /tmp
    #進入容器並啓動bash,同 docker attach 88ec626ba223
    docker exec -it /bin/bash
    

docker exec -it 容器ID bash命令

O)拷貝文件

返回目錄

  1. 使用:
    docker cp [選項] 容器:源路徑 目標路徑|-從容器拷貝到主機
    docker cp [選項] 源路徑|- 容器:目標路徑從主機拷貝到容器
  2. 選項:
      --detach-keys string   Override the key sequence for detaching a container
      --no-stdin             Do not attach STDIN
      --sig-proxy            Proxy all received signals to the process (默認 true)
    
  3. 舉例:
    #拷貝容器中/tmp/xxx.log文件到主機/home/目錄下
    docker cp 88ec626ba223:/tmp/xxx.log /home/
    

P)重命名容器

返回目錄

  1. 使用方式:docker rename 容器 新名字

Q)創建鏡像(從容器生成新鏡像)

返回目錄

  1. 使用方式:docker commit [選項] 容器ID [新鏡像名[:標籤]]
  2. 選項:
      -a, --author string    作者信息 (e.g., "John Hannibal Smith <[email protected]>")
      -c, --change list      將 Dockerfile 指令應用於創建映像
      -m, --message string   描述信息
      -p, --pause            提交期間暫停容器(默認 true)
    
  3. 舉例:
    docker commit -m="myImg" -a="L" 88ec626ba223 myImage:0.0.1
    

三、dockerfile

返回目錄
規則:

  1. 每條保留指令都必須用大寫字母,後面至少有一個參數
  2. 指令按照從上到下的順序執行
  3. # 表示註釋
  4. 每條指令都會創建一個新的鏡像層,並對鏡像進行提交

1. 保留字指令

返回目錄

保留字 說明
FROM 基礎鏡像,當前新鏡像是基於哪個鏡像
基礎鏡像(scratch)大部分的鏡像是在基礎鏡像上安裝和配置需要安裝的軟件構建出來
例:FROM scratch
MAINTAINER 鏡像維護者的名字和電子郵箱
RUN 容器構建時需要運行的命令
EXPOSE 當前容器對外暴露的端口
WORKDIR 指定在創建容器後,終端默認進入的目錄,不指定爲根目錄
ENV 構建過程中設置環境變量
ADD 將宿主機目錄下的文件複製進鏡像並自動處理URL和解壓tar壓縮包
COPY 複製文件到鏡像中。將從構建上下文目錄中<源路徑>的文件/目錄複製到新的一層的鏡像內的<目標路徑>位置
VOLUME 容器數據卷,用於數據保存和持久化工作
CMD 指定容器啓動時要運行的命令,可有多個但只有最後一個生效,會被 docker run 的 COMMAND參數替換
ENTRYPOINT 指定容器啓動時要運行的命令(追加,添加參數用)
ONBUILD 當構建一個被繼承的dockerfile時運行的命令。當被繼承後父鏡像的onbuild被除法
USER 鏡像的用戶權限

2. 自定義鏡像

返回目錄
CentOS 當虛擬機用

FROM centos
ENV PATH /tmp
WORKDIR $PATH
RUN yum -y install vim #支持vim
RUN yum -y install net-tools #支持ipconfig
EXPOSE 9090
CMD /bin/bash

node 的簡單部署

FROM node:12

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . .

EXPOSE 8080
CMD [ "node", "server.js" ]

3. .dockerignore

忽略配置文件

node_modules
npm-debug.log

4. build 構建鏡像

返回目錄

  1. 使用方式:docker build [選項] 路徑 | URL | -
  2. 選項:
          --add-host list           添加自定義主機到IP的映射 (host:ip)
          --build-arg list          設置構建時(build-time)變量
          --cache-from strings      要視爲緩存源的鏡像 
          --cgroup-parent string    容器的可選父容器組(cgroup)
          --compress                使用 gzip 壓縮構建內容
          --cpu-period int          限制 CPU CFS(完全公平調度程序)週期
          --cpu-quota int           限制CPU CFS(完全公平調度程序)配額
      -c, --cpu-shares int          CPU 共享(相對權重)
          --cpuset-cpus string      允許執行的 CPU (0-3, 0,1)
          --cpuset-mems string      允許執行的內存 (0-3, 0,1)
          --disable-content-trust   跳過鏡像驗證 (默認 true)
      -f, --file string             Dockerfile 的名字 (默認 'PATH/Dockerfile')
          --force-rm                始終移除中間容器
          --iidfile string          將鏡像 ID 寫入文件
          --isolation string        容器隔離技術
          --label list              爲鏡像設置元數據(metadata)
      -m, --memory bytes            內存限制
          --memory-swap bytes       Swap limit equal to memory plus swap: '-1' to enable unlimited swap
          --network string          爲構建期間的 RUN 指令設置網絡模式 (默認 "default")
          --no-cache                構建鏡像時不使用緩存
          --platform string         如果服務器是多平臺,則設置平臺
          --pull                    總是嘗試拉取較新版本的鏡像
      -q, --quiet                   構建成功時不輸出和打印鏡像 ID
          --rm                      成功構建後刪除中間容器 (默認 true)
          --security-opt strings    安全選項
          --shm-size bytes          /dev/shm 的大小
          --squash                  將新構建的層壓縮爲單個新層
          --stream                  Stream attaches to server to negotiate build context
      -t, --tag list                'name:tag' 中包含名稱和可選的標籤
          --target string           Set the target build stage to build.
          --ulimit ulimit           Ulimit options (默認 [])
    
  3. 舉例:
    docker build -f /mydocker/dockerfile -t myImages/centos .
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章