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
    名称值类型说明
    starsint镜像获得的星数
    is-automatedboolean是否是自动构建的镜像
    is-officialboolean是否是官方镜像
    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

    名称值类型说明
    danglingboolean悬空
    labellabel=<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 <hannibal@a-team.com>")
      -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 .
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值