Docker 常用命令 与 Dockerfile

本文链接: https://xiets.blog.csdn.net/article/details/122866186

相关文章: Docker 安装与命令索引 --help

1. 镜像管理: docker image

docker image 帮助信息:

$ docker image       

Usage:  docker image COMMAND

Manage images

Commands:
  build       Build an image from a Dockerfile
  history     Show the history of an image
  import      Import the contents from a tarball to create a filesystem image
  inspect     Display detailed information on one or more images
  load        Load an image from a tar archive or STDIN
  ls          List images
  prune       Remove unused images
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rm          Remove one or more images
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE

Run 'docker image COMMAND --help' for more information on a command.

1.1 拉取镜像: docker image pull

可简写为 docker pull,从注册服务器中拉取镜像或仓库:

$ docker image pull --help

Usage:  docker [image] pull [OPTIONS] NAME[:TAG|@DIGEST]

Pull an image or a repository from a registry

Options:
  -a, --all-tags                Download all tagged images in the repository
        --disable-content-trust Skip image verification (default true)
        --platform string       Set platform if server is multi-platform
                                capable
  -q, --quiet                   Suppress verbose output

拉取 ubuntu 镜像,默认拉取 latest 标签:

$ docker image pull ubuntu
# 或
$ docker pull ubuntu

# 拉取指定标签版本
$ docker pull ubuntu:tag_name

拉取 docker/getting-started

$ docker pull docker/getting-started

# 直接运行一个容器,如果本地没有对应镜像也会自动拉取
$ docker run -d -p 80:80 docker/getting-started

如果拉起的是私有仓库需要先登录,运行 docker login,输入用户名和密码,如果已登录则会打印已登录成功的信息。

需要退出登录,运行 docker logout

1.2 推送镜像: docker image push

可简写为 docker push,推送镜像或仓库到注册服务器,推送前需要先登录 (docker login)。

$ docker image push --help

Usage:  docker image push [OPTIONS] NAME[:TAG]

Push an image or a repository to a registry

Options:
  -a, --all-tags                Push all tagged images in the repository
      --disable-content-trust   Skip image signing (default true)
  -q, --quiet                   Suppress verbose output
  
# 命令示例
$ docker image push image_name:tag
$ docker image push -a image_name

推送的镜像需要在注册服务器已创建对应的仓库,创建仓库

  1. 打开 https://hub.docker.com/repositories
  2. 点击 Create Repository,输入仓库名,如: docker_username/image_name,其中 docker_username 是注册服务器的用户名(固定的仓库名前缀),只需要输入 image_name 即可。
  3. 选择 公有(Public)私有(Private),点击 Create 创建仓库。

推送仓库示例:

# 推送前需要先打一个标签, 为了让 镜像仓库名称 与 注册服务器上创建的仓库名称 一致,
# 并且可以重命名标签名, 相当于复制了一份然后新起了一个名称 (镜像ID还是没有改变)
$ docker tag local_image:tagname docker_username/image_name:tagname

# 登录注册服务器
$ docker login

# 推送 本地镜像仓库 到 注册服务器
$ docker push docker_username/image_name:tagname

1.3 列出镜像: docker image ls

可简写为 docker images,列出已下载的镜像:

$ docker image ls
# 或
$ docker images

1.4 删除镜像: docker image rm

可简写为 docker rmi,删除一个或多个镜像:

$ docker image rm --help

Usage:  docker image rm [OPTIONS] IMAGE [IMAGE...]

Remove one or more images

Aliases:
  rm, rmi, remove

Options:
  -f, --force      Force removal of the image
      --no-prune   Do not delete untagged parents

删除 ubuntu 镜像:

$ docker image rm ubuntu
# 或
$ docker rmi ubuntu

1.6 保存镜像: docker image save

可简写为 docker save,保存一个或多个镜像到 tar 存档(可以把多个镜像保存到同一个 tar 存档文件中):

$ docker image save --help

Usage:  docker image save [OPTIONS] IMAGE [IMAGE...]

Save one or more images to a tar archive (streamed to STDOUT by default)

Options:
  -o, --output string   Write to a file, instead of STDOUT

保存 ubuntu 镜像到本地,保存为 ubuntu.tar

$ docker image save -o ubuntu.tar ubuntu
# 或
$ docker save ubuntu > ubuntu.tar

1.5 加载镜像: docker image load

可简写为 docker load,从 tar 存档或 SDTIN 中加载镜像:

docker image load --help

Usage:  docker image load [OPTIONS]

Load an image from a tar archive or STDIN

Options:
  -i, --input string   Read from tar archive file, instead of STDIN
  -q, --quiet          Suppress the load output

从本地文件 ubuntu.tar 加载镜像:

$ docker image load -i ubuntu.tar
# 或
$ cat ubuntu.tar | docker image load
# 或
$ docker image load < ubuntu.tar

1.7 镜像详情: docker image inspect

可简写为 docker inspect,查看镜像的详细信息(镜像ID、默认启动脚本/命令、环境变量、相关配置等):

Usage:  docker image inspect [OPTIONS] IMAGE [IMAGE...]

# 查询 ubuntu 镜像的详细信息
$ docker image inspect ubuntu

# 查询指定字段, 查询 [{"Id": *}] 字段
$ docker image inspect -f "{{.Id}}" ubuntu
sha256:a457a7...

# 查询字段 [{"ContainerConfig": {"Env": *}}]
$ docker image inspect -f "{{.ContainerConfig.Env}}" ubuntu
[PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin]

# 查询字段 [{"ContainerConfig": {"Cmd": *}}]
$ docker image inspect -f "{{.ContainerConfig.Cmd}}" ubuntu
[/bin/sh -c #(nop)  CMD ["bash"]]

# 查询字段 [{"Architecture": *}]
$ docker image inspect -f "{{.Architecture}}" ubuntu    
arm64

1.8 构建镜像: docker image build

可简写为 docker build,根据 Dockerfile 文件构建一个镜像,帮助信息:

$ docker image build --help

Usage:  docker image build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

Options:
      --add-host list           Add a custom host-to-IP mapping (host:ip)
      --build-arg list          Set build-time variables
      --cache-from strings      Images to consider as cache sources
      --disable-content-trust   Skip image verification (default true)
  -f, --file string             Name of the Dockerfile (Default is
                                'PATH/Dockerfile')
      --iidfile string          Write the image ID to the file
      --isolation string        Container isolation technology
      --label list              Set metadata for an image
      --network string          Set the networking mode for the RUN
                                instructions during build (default "default")
      --no-cache                Do not use cache when building the image
  -o, --output stringArray      Output destination (format:
                                type=local,dest=path)
      --platform string         Set platform if server is multi-platform
                                capable
      --progress string         Set type of progress output (auto, plain,
                                tty). Use plain to show container output
                                (default "auto")
      --pull                    Always attempt to pull a newer version of
                                the image
  -q, --quiet                   Suppress the build output and print image
                                ID on success
      --secret stringArray      Secret file to expose to the build (only
                                if BuildKit enabled):
                                id=mysecret,src=/local/secret
      --ssh stringArray         SSH agent socket or keys to expose to the
                                build (only if BuildKit enabled) (format:
                                default|<id>[=<socket>|<key>[,<key>]])
  -t, --tag list                Name and optionally a tag in the
                                'name:tag' format
      --target string           Set the target build stage to build.

构建镜像示例:

# Dockerfile 文件内容
$ cat Dockerfile 
FROM ubuntu
RUN apt update && apt install -y vim

# 构建镜像
# (仓库)镜像名为 mylibrary/ubt, 标签为 v2 (如果没有, 则默认为 latest 标签)
# . 表示构建时的本地工作目录为当前目录, 默认使用此目录下的 Dockerfile 文件构建
$ docker build -t mylibrary/ubt:v2 .

# 构建成功后, 查看本地镜像
$ docker images

2. 容器管理: docker container

docker container 帮助信息:

% docker container

Usage:  docker container COMMAND

Manage containers

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  commit      Create a new image from a container's changes
  cp          Copy files/folders between a container and the local filesystem
  create      Create a new container
  diff        Inspect changes to files or directories on a container's filesystem
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  inspect     Display detailed information on one or more containers
  kill        Kill one or more running containers
  logs        Fetch the logs of a container
  ls          List containers
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  prune       Remove all stopped containers
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  run         Run a command in a new container
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  top         Display the running processes of a container
  unpause     Unpause all processes within one or more containers
  update      Update configuration of one or more containers
  wait        Block until one or more containers stop, then print their exit codes

Run 'docker container COMMAND --help' for more information on a command.

2.1 创建容器: docker container create

可简写为 docker create,创建一个新的容器:

Usage:  docker container create [OPTIONS] IMAGE [COMMAND] [ARG...]

命令用法与 docker container run 基本相同,参考 「运行容器: docker container run」。

2.2 运行容器: docker container run

可简写为 docker run,创建并运行一个新容器,等价于 docker create 然后 docker start CONTAINER。创建/运行容器时如果镜像没有下载,会先下载对应的镜像。

常用参数:

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

-d, --detach            # 在后台运行容器并打印容器ID
-i, --interactive       # 保持 STDIN 打开, 即使没有附加
-t, --tty               # 分配一个终端, 通常搭配 -t 使用, 如 -it 表示分配一个终端并保持标准输入打开

-e, --env list          # 设置环境变量, 如: -e VAR1=value1 --env VAR2=value2
                        # 只有名称没有等号, 如 --env USER 表示引用宿主机本地的环境变量 USER=$USER
--env-file list         # 从一个文件中读取环境变量, 如: --env-file ./env_list.txt
                        # 文件内容为每行一个环境变量 (#号开头的行为注释, 将被忽略)
                        # VAR=value     表示值为名称为 VAR, 值为 value 的环境变量
                        # USER          只有名称没有等号, 则表示引用宿主机本地的环境变量 USER=$USER

-p, --publish list      # 发布容器的端口到宿主机 (端口映射: 宿主机 -> 容器), 格式: -p [ip:]port:port[/type], 如:
                        # -p 80:8080            宿主机80端口 映射到 容器的8080端口, 默认宿主机监听的IP为 0.0.0.0(即所有IP), 默认类型为 TCP
                        # -p 127.0.0.1:80:80    可以指定宿主机监听的 IP, 表示 127.0.0.1:8080->80/tcp
                        # -p 8022:22/tcp        可以指定端口类型, 表示 0.0.0.0:8022->22/tcp
                        # -p 3050:8050/udp      表示 0.0.0.0:3050->8050/udp
                        # -p 9000:9000/sctp     表示 0.0.0.0:9000->9000/sctp
--expose list           # 暴露容器的端口或端口范围, 格式: --expose port[-port][/type],
                        # --expose 80           表示暴露容器的 80 端口, 默认为 TCP 类型
                        # --expose 0-65535      暴露容器的端口范围 0-65535
                        # --expose 8080/udp     可指定端口类型
-P, --publish-all       # 发布 --expose 暴露的端口所有端口到宿主机, 宿主机中将随机生成端口进行映射

--name string           # 指定容器名称
-h, --hostname string   # 指定容器的主机名(默认使用容器ID作为主机名)

-w, --workdir string    # 启动后容器内的工作目录, 如: -w /root (如果目录不存在, 则自动创建)
-v, --volume list       # 绑定挂载卷, 把本地目录映射到容器, 格式: -v host_dir_path:container_dir_path, 如:
                        # -v /my_dir:/root/my_dir 如果宿主机本地或容器内目录不存在都将会自动创建
                        
-u, --user string       # 使用指定用户身份(用户必须存在), 格式: -u <name|uid>[:<group|gid>]

--mac-address string    # 指定容器的 MAC 地址, 如: --mac-address 92:d0:c6:0a:29:33
--network network       # 指定容器连接的网络 (可以先创建一个网络, 再使用此网络并设置固定 IP 地址)
--ip string             # 指定容器的 IPv4 地址, 如: --ip=172.30.100.104
--ip6 string            # 指定容器的 IPv6 地址, 如: --ip6=2001:db8::33
--dns list              # 设置自定义 DNS, 如: --dns=8.8.8.8 --dns=119.29.29.29

--rm                    # 容器停止(退出)后自动删除

--restart string        # 容器退出后的重启策略, 可取值:
                        # no                        容器退出时不自动重启 (默认设置)
                        # on-failure[:max-retries]  仅当容器以非0状态退出时才重新启动, 可选限制最大重启次数
                        # unless-stopped            除非明确停止或 Docker 本身停止或重新启动,否则重新启动容器。
                        # always                    无论退出状态如何, 始终重新启动容器。当指定 always 时, 
                        #                           Docker 守护程序将尝试无限期地重新启动容器。
                        #                           无论容器的当前状态如何, 容器也将始终在守护程序启动时启动。

--entrypoint string     # 替换镜像中默认的 ENTRYPOINT 可执行文件, 文件立即必须容器内的一个可执行文件, 如: --entrypoint /bin/sh
[COMMAND] [ARG...]      # 拼接到 IMAGE 镜像名称后面的命令和参数

重启策略:restart-policies—restart

ENTRYPOINT[COMMAND] [ARG...] 的区别:

  • 如果有 ENTRYPOINT 指定的入口点命令文件,则容器启动时将执行此文件,镜像名称后面的 [COMMAND] [ARG…] 将作为参数列表传给 ENTRYPOINT,即 $ ENTRYPOINT [COMMAND] [ARG...]
  • 如果没有 ENTRYPOINT,则镜像后面的 [COMMAND] [ARG…] 将作为容器启动时执行的命令,即 $ COMMAND [ARG...]

容器启动命令 (ENTRYPOINT 或 [COMMAND] [ARG…]) 的进程执行完毕后,容器的生命周期即结束,即容器将停止(退出)。

命令示例:

# 在后台运行容器, 并映射 TCP 端口 0.0.0.0:80->80/tcp
docker run -d -p 80:80 docker/getting-started

# 分配终端并保持输入打开, 容器退出时自动删除, 启动后执行 /bin/sh
docker run -it --rm ubuntu /bin/sh

# 设置换变量, 启动后输出所有环境变量
docker run -it --rm -e HELLO=world -e HOME ubuntu env

# 运行 python 镜像容器, 容器后台运行, 容器始终自动重启,
# 宿主机当前目录映射到容器内的 /root/test, 容器工作目录切换到 /root/test,
# 映射端口 0.0.0.0:8000->8000/tcp,
# 启动后执行命令 python3 -m http.server 8000
docker run -d \
           --restart always \
           -v $(pwd):/root/test -w /root/test \
           -p 8000:8000 \
           python \
           python3 -m http.server 8000

帮助信息:

$ docker run --help

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

Run a command in a new container

Options:
      --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                   Add Linux capabilities
      --cap-drop list                  Drop Linux capabilities
      --cgroup-parent string           Optional parent cgroup for the
                                       container
      --cgroupns string                Cgroup namespace to use
                                       (host|private)
                                       'host':    Run the container in
                                       the Docker host's cgroup namespace
                                       'private': Run the container in
                                       its own private cgroup namespace
                                       '':        Use the cgroup
                                       namespace as configured by the
                                                  default-cgroupns-mode
                                       option on the daemon (default)
      --cidfile string                 Write the container ID to the file
      --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
      --domainname string              Container NIS domain name
      --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
      --gpus gpu-request               GPU devices to add to the
                                       container ('all' to pass all GPUs)
      --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                           Print usage
  -h, --hostname string                Container host name
      --init                           Run an init inside the container
                                       that forwards signals and reaps
                                       processes
  -i, --interactive                    Keep STDIN open even if not attached
      --ip string                      IPv4 address (e.g., 172.30.100.104)
      --ip6 string                     IPv6 address (e.g., 2001:db8::33)
      --ipc string                     IPC mode to use
      --isolation string               Container isolation technology
      --kernel-memory bytes            Kernel memory limit
  -l, --label list                     Set meta data on a container
      --label-file list                Read in a line delimited file of labels
      --link list                      Add link to another container
      --link-local-ip list             Container IPv4/IPv6 link-local
                                       addresses
      --log-driver string              Logging driver for the container
      --log-opt list                   Log driver options
      --mac-address string             Container MAC address (e.g.,
                                       92:d0:c6:0a:29:33)
  -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
      --memory-swappiness int          Tune container memory swappiness
                                       (0 to 100) (default -1)
      --mount mount                    Attach a filesystem mount to the
                                       container
      --name string                    Assign a name to the container
      --network network                Connect a container to a network
      --network-alias list             Add network-scoped alias for the
                                       container
      --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                 Tune container pids limit (set -1
                                       for unlimited)
      --platform string                Set platform if server is
                                       multi-platform capable
      --privileged                     Give extended privileges to this
                                       container
  -p, --publish list                   Publish a container's port(s) to
                                       the host
  -P, --publish-all                    Publish all exposed ports to
                                       random ports
      --pull string                    Pull image before running
                                       ("always"|"missing"|"never")
                                       (default "missing")
      --read-only                      Mount the container's root
                                       filesystem as read only
      --restart string                 Restart policy to apply when a
                                       container exits (default "no")
      --rm                             Automatically remove the container
                                       when it exits
      --runtime string                 Runtime to use for this container
      --security-opt list              Security Options
      --shm-size bytes                 Size of /dev/shm
      --sig-proxy                      Proxy received signals to the
                                       process (default true)
      --stop-signal string             Signal to stop a container
                                       (default "SIGTERM")
      --stop-timeout int               Timeout (in seconds) to stop a
                                       container
      --storage-opt list               Storage driver options for the
                                       container
      --sysctl map                     Sysctl options (default map[])
      --tmpfs list                     Mount a tmpfs directory
  -t, --tty                            Allocate a pseudo-TTY
      --ulimit ulimit                  Ulimit options (default [])
  -u, --user string                    Username or UID (format:
                                       <name|uid>[:<group|gid>])
      --userns string                  User namespace to use
      --uts string                     UTS namespace to use
  -v, --volume list                    Bind mount a volume
      --volume-driver string           Optional volume driver for the
                                       container
      --volumes-from list              Mount volumes from the specified
                                       container(s)
  -w, --workdir string                 Working directory inside the container

2.3 列出容器: docker container ls

可简写为 docker ps,列出已创建的容器。

帮助信息:

$ docker container ls --help

Usage:  docker container ls [OPTIONS]

List containers

Aliases:
  ls, ps, list

Options:
  -a, --all             Show all containers (default shows just running)
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print containers using a Go template
  -n, --last int        Show n last created containers (includes all states) (default -1)
  -l, --latest          Show the latest created container (includes all states)
      --no-trunc        Don't truncate output
  -q, --quiet           Only display container IDs
  -s, --size            Display total file sizes

命令示例:

# 列出正在运行的容器
$ docker ps

# 列出所有容器
$ docker ps -a

2.4 删除容器: docker container rm

可简写为 docker rm

# 命令格式
Usage:  docker container rm [OPTIONS] CONTAINER [CONTAINER...]

# 命令示例
$ docker rm mycontainer

2.5 启动容器: docker container start

可简写为 docker start

# 命令格式
Usage:  docker container start [OPTIONS] CONTAINER [CONTAINER...]

# 命令示例
$ docker start mycontainer

2.6 停止容器: docker container stop

可简写为 docker stop

# 命令格式
Usage:  docker container stop [-t/--time SEC] CONTAINER [CONTAINER...]

# 命令示例: 停止容器, 等待 5 秒如果还没有停止则直接终止(kill)
$ docker stop -t 5 mycontainer

# 命令示例: 停止容器 (默认 -t=10)
$ docker stop mycontainer

2.7 重启容器: docker container restart

可简写为 docker restart

# 命令格式
Usage:  docker container restart [-t/--time SEC] CONTAINER [CONTAINER...]

# 命令示例
$ docker restart mycontainer

2.8 终止容器: docker container kill

可简写为 docker kill

# 命令格式
Usage:  docker container kill [OPTIONS] CONTAINER [CONTAINER...]

# 命令示例
$ docker kill mycontainer

2.9 显示容器进程: docker container top

可简写为 docker top,显示容器中正在运行的进程。

# 命令格式
Usage:  docker container top CONTAINER [ps OPTIONS]

# 命令示例
docker top mycontainer

2.10 显示容器资源使用: docker container stats

可简写为 docker stats

命令帮助:

$ docker stats --help

Usage:  docker stats [OPTIONS] [CONTAINER...]

Display a live stream of container(s) resource usage statistics

Options:
  -a, --all             Show all containers (default shows just running)
      --format string   Pretty-print images using a Go template
      --no-stream       Disable streaming stats and only pull the first result
      --no-trunc        Do not truncate output

命令示例:

# 显示 正在运行 的容器资源使用
$ docker stats

# 显示 正在运行 的容器资源使用 (禁用流统计, 只拉第一个结果)
$ docker stats --no-stream

# 显示 所有 容器资源使用
$ docker stats -a

# 显示 指定容器 的资源使用
$ docker stats mycontainer

2.11 重命名容器: docker container rename

可简写为 docker rename

# 命令格式
Usage:  docker container rename CONTAINER NEW_NAME

# 命令示例
$ docker rename my_container my_new_container

2.12 在容器中运行命令: docker container exec

可简写为 docker exec

帮助信息:

$ docker container exec --help

Usage:  docker container exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

Options:
  -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
      --env-file list        Read in a file of 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

命令示例:

# 在容器中运行命令, 分配一个终端并保持输入打开
$ docker exec -it mycontainer /bin/sh

# 指定工作目录
$ docker exec -it -w /root mycontainer pwd

# 在容器后台运行命令
$ docker exec -d mycontainer COMMAND [ARG...]

2.13 容器与本地之间复制文件: docker container cp

可简写为 docker cp,支持 容器 与 宿主机本地 之间相互复制文件/文件夹。

# 命令格式
Usage:  docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
        docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH

# 从前面参数路径 复制到 后面参数路径, 容器内路径需要加 CONTAINER: 前缀

命令示例:

# 将 容器内的/bin文件夹 复制到 宿主机本地./bin目录
$ docker cp mycontainer:/bin ./bin

# 将 宿主机本地的./demo.jpg 文件复制到 容器内的/root/目录下命名不改变
$ docker cp ./demo.jpg mycontainer:/root/

# 将 宿主机本地的./demo.jpg 文件复制到 容器内的/root/目录下命名为aa.jpg
$ docker cp ./demo.jpg mycontainer:/root/aa.jpg

# 将 宿主机本地的./aa_dir 文件夹复制到 容器内的/root/目录下(保存为/root/aa_dir)
$ docker cp ./aa_dir mycontainer:/root/

2.14 列出容器端口映射: docker container port

可简写为 docker port

# 命令格式
Usage:  docker container port CONTAINER [PRIVATE_PORT[/PROTO]]

# 命令示例
$ docker port mycontainer

2.15 显示容器详细信息: docker container inspect

可简写为 docker inspect

# 命令格式
Usage:  docker container inspect [OPTIONS] CONTAINER [CONTAINER...]

# 命令示例
$ docker inspect mycontainer

# 查询指定字段, 查询 [{"Id": *}] 字段
$ docker inspect -f "{{.Id}}" mycontainer
a457a7...

# 查询字段 [{"Config": {"Env": *}}]
$ docker inspect -f "{{.Config.Env}}" mycontainer
[PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin]

# 查询字段 [{"Config": {"Cmd": *}}]
$ docker inspect -f "{{.Config.Cmd}}" mycontainer
[/bin/sh -c #(nop)  CMD ["bash"]]

# 查询字段 [{"State": {"Status": *}]
$ docker inspect -f "{{.State.Status}}" mycontainer
exited

# 查询容器重启策略 [{"HostConfig": {"RestartPolicy": *}]
$ docker inspect -f "{{.HostConfig.RestartPolicy}}" mycontainer

2.16 导出容器文件系统: docker container export

可简写为 docker export,把容器的文件系统打包成 tar 归档文件导出,导出后可使用 docker [image] import] 导入为新的镜像。

# 命令格式
Usage:  docker export [OPTIONS] CONTAINER

# 导出容器保存为 mycontainer.tar (默认导出到 STDOUT)
$ docker export -o mycontainer.tar mycontainer
# 或
$ docker export mycontainer > mycontainer.tar

docker import 命令:

# 命令格式
Usage:  docker import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]

# 导入容器文件系统创建新的镜像
$ docker import mycontainer.tar image_name:tag
# 或
$ cat mycontainer.tar | docker import - image_name:tag
# 或
$ docker import - image_name:tag < test.tar

2.17 更新容器配置: docker container update

可简写为 docker update,更新容器的配置,如 CPU、内存的使用限制,重启策略等。

帮助信息:

$ docker container update --help

Usage:  docker container update [OPTIONS] CONTAINER [CONTAINER...]

Update configuration of one or more containers

Options:
      --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
      --pids-limit int             Tune container pids limit (set -1 for
                                   unlimited)
      --restart string             Restart policy to apply when a
                                   container exits

命令示例:

# 容器设置为始终自动重启
$ docker update --restart always mycontainer

2.18 容器改变创建新镜像: docker container commit

可简写为 docker commit,根据容器的改变提交为新的一个镜像,提交后可使用 docker [image] pull 推送镜像到注册服务器。

Usage:  docker container commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

# 提交容器镜像改变, 创建 image_name:tag 镜像
$ docker commit mycontainer image_name:tag

2.19 暂停容器: docker container pause

可简写为 docker pause

# 命令格式
Usage:  docker container pause CONTAINER [CONTAINER...]

# 命令示例
docker pause mycontainer

2.20 恢复容器: docker container unpause

可简写为 docker unpause

# 命令格式
Usage:  docker container unpause CONTAINER [CONTAINER...]

# 命令示例
docker unpause mycontainer

3. 网络管理: docker network

docker network 帮助信息:

$ docker network     

Usage:  docker network COMMAND

Manage networks

Commands:
  connect     Connect a container to a network
  create      Create a network
  disconnect  Disconnect a container from a network
  inspect     Display detailed information on one or more networks
  ls          List networks
  prune       Remove all unused networks
  rm          Remove one or more networks

Run 'docker network COMMAND --help' for more information on a command.

3.1 创建网络: docker network create

帮助文档:

docker network create --help

Usage:  docker network create [OPTIONS] NETWORK

Create a network

Options:
      --attachable           Enable manual container attachment
      --aux-address map      Auxiliary IPv4 or IPv6 addresses used by Network driver (default map[])
      --config-from string   The network from which to copy the configuration
      --config-only          Create a configuration only network
  -d, --driver string        Driver to manage the Network (default "bridge")
      --gateway strings      IPv4 or IPv6 Gateway for the master subnet
      --ingress              Create swarm routing-mesh network
      --internal             Restrict external access to the network
      --ip-range strings     Allocate container ip from a sub-range
      --ipam-driver string   IP Address Management Driver (default "default")
      --ipam-opt map         Set IPAM driver specific options (default map[])
      --ipv6                 Enable IPv6 networking
      --label list           Set metadata on a network
  -o, --opt map              Set driver specific options (default map[])
      --scope string         Control the network's scope
      --subnet strings       Subnet in CIDR format that represents a network segment

命令示例:

# 创建一个网络 (默认驱动管理为 --driver=bridge)
$ docker network create \
    --subnet=192.168.0.0/16 \       # 子网网段
    --ip-range=192.168.100.0/24 \   # IP地址范围 (必须在 subnet 范围内, 没有指定则与 subnet 一致)
    --gateway=192.168.100.100 \     # 子网网关 (可设置多个 subnet 和 gateway)
    mynet                           # 网络名称

# 创建容器时指定 网络 和 固定IP地址
docker run --rm -it --network=mynet --ip=192.168.100.200 busybox ifconfig

(32位) IP 地址范围描述:

  • 192.168.0.0/16 表示以 192.168.0.0 开始,前 16 位不变,即表示范围 192.168.0.0 ~ 192.168.255.255
  • 192.168.100.0/24 表示以 192.168.100.0 开始,前 24 位不变,即表示范围 192.168.100.0 ~ 192.168.100.255

如果宿主机网络已支持 IPv6,但容器网络不支持 IPv6,可以尝试 Docker 启用 IPv6

(0)确认宿主机已有 IPv6 地址:

# 查看 宿主机(eth0) inet6 地址
$ ifconfig

(1)编辑 vim /etc/docker/daemon.json (如果文件不存在则创建),输入内容:

{
    "ipv6": true,
    "fixed-cidr-v6": "fd00::/80",
    "experimental": true,
    "ip6tables": true
}

(2)重启 Docker Engine:

# 重启 docker 服务
$ systemctl restart docker

# 查看 docker0 分配的 inet6 地址
$ ifconfig

(3)创建容器,测试 IPv6:

# 强制使用 IPv6 PING
$ docker run --rm -it busybox ping -6 -c 3 ipv6-test.com

# 查看容器是否分配 inet6 地址
$ docker run --rm -it busybox ifconfig

3.2 列出网络: docker network ls

$ docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
bc3*********   bridge    bridge    local
876*********   host      host      local
ff3*********   mynet     bridge    local
797*********   none      null      local

3.3 连接网络: docker network connect

帮助信息:

docker network connect --help   

Usage:  docker network connect [OPTIONS] NETWORK CONTAINER

Connect a container to a network

Options:
      --alias strings           Add network-scoped alias for the container
      --driver-opt strings      driver options for the network
      --ip string               IPv4 address (e.g., 172.30.100.104)
      --ip6 string              IPv6 address (e.g., 2001:db8::33)
      --link list               Add link to another container
      --link-local-ip strings   Add a link-local address for the container

命令示例:

# 连接 容器(mycontainer) 到 网络(mynet) 并指定固定IP
$ docker network connect --ip=192.168.100.123 mynet mycontainer

# 连接成功后, 容器内将多一个网络 (eth1)
$ docker exec -it mycontainer ifconfig

3.4 断连网络: docker network disconnect

# 命令格式, -s 表示强制断开
Usage:  docker network disconnect [-f/--force] NETWORK CONTAINER

# 命令示例: 将容器(mycontainer) 从 网络(mynet) 断开
$ docker network disconnect mynet mycontainer

# 断开成功后, 容器内将少一个网络 (eth1)
$ docker exec -it mycontainer ifconfig

3.5 移除网络: docker network rm/prune

# 命令格式
Usage:  docker network rm NETWORK [NETWORK...]
Usage:  docker network prune [OPTIONS]

# 命令示例: 移除网络(mynet), 移除前需断开与容器的网络连接
$ docker network rm mynet

# 移除所有没有在使用的网络
$ docker network prune

3.6 网络详情: docker network inspect

帮助信息:

docker network inspect --help

Usage:  docker network inspect [OPTIONS] NETWORK [NETWORK...]

Display detailed information on one or more networks

Options:
  -f, --format string   Format the output using the given Go template
  -v, --verbose         Verbose output for diagnostics

命令示例:

# 查看网络(mynet)的详细信息
$ docker network inspect mynet

# 查看ID
$ docker network inspect -f {{.Id}} mynet  

# 查看已连接到此网络(mynet)的容器
$ docker network inspect -f {{.Containers}} mynet

4. 卷管理: docker volume

docker volume 帮助信息:

$ docker volume

Usage:  docker volume COMMAND

Manage volumes

Commands:
  create      Create a volume
  inspect     Display detailed information on one or more volumes
  ls          List volumes
  prune       Remove all unused local volumes
  rm          Remove one or more volumes

Run 'docker volume COMMAND --help' for more information on a command.

4.1 创建卷: docker volume create

创建一个卷,创建容器时把此卷映射(-v)到容器内的目录(类似于把宿主机本地的目录映射到容器内的目录),可实现多个容器之间互相共享文件。

帮助信息:

$ docker volume create --help

Usage:  docker volume create [OPTIONS] [VOLUME]

Create a volume

Options:
  -d, --driver string   Specify volume driver name (default "local")
      --label list      Set metadata for a volume
  -o, --opt map         Set driver specific options (default map[])

命令示例:

# 创建一个名为 hello 的卷
$ docker volume create hello

# 创建容器时 卷(hello) 映射到容器的 /world 目录(没有则自动创建)
$ docker run --rm -it -v hello:/world -w /world busybox touch hi.txt

# 再创建一个容器映射此卷, 查看卷内文件
$ docker run --rm -it -v hello:/root/hi alpine ls /root/hi
hi.txt

4.2 列出卷: docker volume ls

# 列出所有卷
$ docker volume ls
DRIVER    VOLUME NAME
local     hello

4.3 卷详情: docker volume inspect

# 查询卷详情
$ docker volume inspect volume_name

4.4 删除卷: docker volume rm/prune

# 删除卷
$ docker volume rm volume_name

# 删除本地所有未使用的卷
$ docker volume prune

5. 系统管理: docker system

docker system 帮助信息:

$ docker system

Usage:  docker system COMMAND

Manage Docker

Commands:
  df          Show docker disk usage
  events      Get real time events from the server
  info        Display system-wide information
  prune       Remove unused data

Run 'docker system COMMAND --help' for more information on a command.

5.1 磁盘使用: docker system df

显示磁盘使用状态:

$ docker system df
TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          8         1         1.009GB   1.009GB (100%)
Containers      1         1         1.397MB   0B (0%)
Local Volumes   1         0         0B        0B
Build Cache     2         0         0B        0B

5.2 系统信息: docker system info

显示系统信息:容器数量、镜像数量、版本信息、操作系统、CPU架构 等信息

$ docker system info

5.3 移除数据: docker system prune

移除未使用的数据:

$ docker system prune
WARNING! This will remove:
  - all stopped containers
  - all networks not used by at least one container
  - all dangling images
  - all dangling build cache

Are you sure you want to continue? [y/N]

6. 构建镜像文件: Dockerfile

Dockerfile 文件用于 docker build 构建镜像时用的描述文件,由一些列指令(instruction)组成,每一条指令运行后都会在镜像中生成一个层。

官方文档:

Dockerfile 常用指令:

  1. FROM:指定一个镜像作为基础镜像。如果不以任何镜像为基础,可以引用空白镜像 FROM scratch
  2. RUN:构建镜像时在(层)容器中运行命令,指令执行完成后提交容器改变形成新的一层。
  3. CMD:镜像构建好后,创建容器,容器启动时默认执行的命令。
  4. LABEL:将元数据添加到镜像,如 作者、版本、描述信息等。
  5. ENV:在容器中 设置环境变量,ENV 设置的环境变量在 ADD、COPY、ENV、EXPOSE、FROM、LABEL、STOPSIGNAL、USER、VOLUME、WORKDIR、ONBUILD 等指令中可以使用(指令是在镜像容器中运行的,不能引用宿主机本地的环境变量)。
  6. ARG:定义一个变量(可以指定默认值),在执行 docker build 命令时可以传入参数给此变量赋值(--build-arg <ARG_NAME>=<value>),后续指令可以使用 ${ARG_NAME} 引用变量的值。与 ENV 不同,ARG 设置的变量不会保存到最终的镜像中,ARG 变量仅在构建过程中(包括在执行 RUN 指令的容器中)有效。
  7. COPY:复制文件/文件夹到镜像的(新层)文件系统。
  8. ADD:添加文件/文件夹到镜像的(新层)文件系统(支持自动解压缩)。
  9. ENTRYPOINT:容器启动时执行的命令,有此参数时 CMD 指令内容的将传递给 ENTRYPOINT 命令的作为参数。
  10. EXPOSE:创建容器时打算发布(暴露)的(TCP/UDP)端口。
  11. VOLUME:创建容器时自动创建卷并挂载到指定挂载点。
  12. USER:改变运行 RUN、CMD、ENTRYPOINT 等指令的用户身份,以及容器启动时默认的用户身份,用户必须是容器内已创建的。没有指定用户,默认为 root 用户。
  13. WORKDIR:改变后面的指令运行时的工作目录(容器内目录,运行容器时的默认工作目录也是此目录),可以是相对路径(相对于上一条 WORKDIR 指令的路径),默认路径为 /
  14. ONBUILD:当此镜像被其他 Dockerfile 作为基础镜像被引用时触发的指令(如 RUNCOPY 等),此次构建不执行,在其他 Dockerfile 引用时的 FROM 指令中执行。
  15. SHELL:覆盖用于执行命令时默认用的 shell,Linux 默认是 ["/bin/sh", "-c"],Windows 的默认是 ["cmd", "/S", "/C"]
  16. STOPSIGNAL:设置将被发送到容器以退出容器的系统调用信号(容器停止信号),默认为 SIGTERM
  17. HEALTHCHECK:容器健康检查指令,告诉 Docker 如何测试容器以检查它是否仍在工作。

简单尝试 (使用 alpine 作为基础镜像构建一个 python 镜像):

# Dockerfile 文件内容
$ cat Dockerfile
FROM alpine
RUN apk update && apk add python3
CMD python3

# 构建镜像, 镜像名保存为 alpine-py, 构建时的上下文路径为当前路径(读取./Dockerfile)
$ docker build -t alpine-py .

# 构建成功后, 查看镜像
$ docker images                    
REPOSITORY  TAG       IMAGE ID       CREATED         SIZE
alpine-py   latest    3129997e5558   3 hours ago     53.5MB
alpine      latest    8e1d7573f448   2 months ago    5.33MB

# 创建容器
$ docker run --rm -it alpine-py   
Python 3.9.7 (default, Nov 24 2021, 21:15:59) 
[GCC 10.3.1 20211027] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

6.1 FROM

FROM:指定一个镜像作为基础镜像。如果不以任何镜像为基础,可以引用空白镜像 FROM scratch。

Dockerfile 必须以 FROM 指令开始(FROM 之前可以使用 ARG 声明变量)。在 Dockerfile 文件中,其他指令可以没有,但 FROM 指令必须要有。

指令格式:

FROM [--platform=<platform>] <image> [AS <name>]
# 或
FROM [--platform=<platform>] <image>[:<tag>] [AS <name>]
# 或
FROM [--platform=<platform>] <image>[@<digest>] [AS <name>]

指令示例:

FROM alpine
ARG VERSION=latest
FROM alpine:${VERSION}

6.2 RUN

RUN:构建镜像时在(层)容器中运行命令,指令执行完成后提交容器改变形成新的一层。

RUN 指令会先创建一个容器,然后在容器中运行命令,完成后提交改变形成新的一层。

如果有多条 RUN 指令,每条指令都会新建容器(使用当前最新镜像)来运行命令,因此多条 RUN 指令的命令将在不同的上下文环境中运行(文件系统会沿用)。

为了避免创建多个文件系统层,建议把多条 RUN 指令合并运行,可以使用续行符 \ 来对命令换行。

RUN 有两种形式:

  • RUN <command> (shell 形式,命令在 shell 中运行,Linux 默认为 /bin/sh -c,Windows 默认为 cmd /S /C)
  • RUN ["executable", "param1", "param2"] (exec 形式)

RUN 指令示例:

RUN apt update && apt install -y vim

FROM ubuntu

RUN apt update && \
    apt install -y vim

使用 exec 形式运行命令:

RUN ["echo", "Hello World"]

# exec 形式运行命令,参数将被解析为 JSON 数组,每个参数两边必须使用双引号(")而不是单引号(')

shell 形式不同,exec 形式不会调用 shell 命令,而是直接运行,这意味着 exec 形式不会发生正常的外壳处理。例如,RUN ["echo", "$HOME"] 不会将 $HOME 替换为对应的环境变量值,而且直接使用字面值。要想 exec 形式运行命令并且进行 shell 处理,可以使用 exec 先运行一个 shell 再由 shell 运行命令,例如:RUN ["sh", "-c", "echo $HOME"]

FROM ubuntu

ENV NAME=test
WORKDIR /root/${NAME}

# 调用默认的 shell, 即 /bin/sh -c "touch \"sh_${NAME}.txt\"", 将创建文件: /root/sh_test.txt
RUN touch "sh_${NAME}.txt"

# 不调用 shell, 将创建文件: 'exec_${NAME}.txt'
RUN ["touch", "exec_${NAME}.txt"]

# 先运行一个 shell, 将创建文件: bash_test.txt
RUN ["/bin/bash", "-c", "touch bash_${NAME}.txt"]

# 输出: bash_test.txt 'exec_${NAME}.txt'   sh_test.txt
CMD ls

构建测试:

$ docker build -t test  .
...

$ docker run --rm -it test
 bash_test.txt	'exec_${NAME}.txt'   sh_test.txt

6.3 CMD

CMD:镜像构建好后,创建容器,容器启动时默认执行的命令。

RUN 指令在镜像构建(docker build)时运行,CMD 指令在容器启动(docker run/start)时运行(作为命令运行或作为参数传递给ENTRYPOINT)。DockerfileCMD 指令只能有一条,如果有多条则最后一条生效。

CMD 指令有三种形式:

  • CMD ["executable", "param1", "param2"] (exec 形式,这是首选形式)
  • CMD ["param1", "param2"] (如果有 ENTRYPOINT,则作为 ENTRYPOINT 的默认参数)
  • CMD command param1 param2 (sell 形式,命令将使用 /bin/sh -c "command param1 param2" 运行)

RUN 指令的形式相同,exec 形式不会调用 shell 命令,也就是不会发生正常的外壳处理。例如,CMD ["echo", "$HOME"] 不会将 $HOME 替换为对应的环境变量值,而且直接使用字面值。要想 exec 形式运行命令并且进行 shell 处理,可以使用 exec 先运行一个 shell 再由 shell 运行命令,例如:CMD ["sh", "-c", "echo $HOME"],与 shell 形式一样,这里是 shell 进行环境变量扩展,而不是 docker。

如果 CMD 用于为ENTRYPOINT 提供默认参数 或 使用 exec 形式运行,指令应该使用 JSON 数组格式指定,且单词两边必须使用双引号(")引起来。

使用 shell 的形式运行,由于是先运行一个 shell 进程,然后在子进程运行命令,因此可能(不同系统可能还不一样)会有 2 个进程。使用 exec 方式运行,由于是直接(在当前进程)运行,因此将只有 1 个进程。

shell 形式示例:

FROM ubuntu
CMD "top" "-d" "1" "-n" "5"
$ docker build -t test_image . 

# 有 2 个进程
$ docker run --rm -it test_image
...
PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND                                          
  1 root      20   0    2060    476    408 S   0.0   0.0   0:00.01 sh                                               
  8 root      20   0    5704   2524   2120 R   0.0   0.1   0:00.00 top 

exec 形式示例:

FROM ubuntu
CMD ["top", "-d", "1", "-n", "5"]
$ docker build -t test_image . 

# 只有 1 个进程
$ docker run --rm -it test_image 
...
PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND                                          
  1 root      20   0    5736   2608   2220 R   0.0   0.1   0:00.01 top   

Linux exec 运行命令的方式:

exec 方式运行命令时,不会启动新的 shell(不会创建新的进程),而是用 被执行的命令 替换当前 shell 进程(PID 不变),并将老进程的上下文环境清理掉,exec 命令后面的其他命令不会再执行。例如,打开一个 shell 终端,运行 exec ls 命令,运行完后,终端将退出。这是因为 运行 exec ls 命令的进程“替换”了原 shell 终端进程,命令结束后,终端也就退出了。

6.4 LABEL

LABEL:将元数据添加到镜像,如 作者、版本、描述信息等。自动继承父镜像(FROM)的标签,相同名称的标签会覆盖前者。

指令格式:

LABEL <key>=<value> <key>=<value> <key>=<value> ...

指令示例:

LABEL "com.example.vendor"="ACME Incorporated"
LABEL com.example.label-with-value="foo"
LABEL version="1.0"
LABEL description="This text illustrates \
that label-values can span multiple lines."

# 可以一个指令添加多个标签
LABEL multi.label1="value1" multi.label2="value2" other="value3"

LABEL multi.label1="value1" \
      multi.label2="value2" \
      other="value3"

6.5 ENV

ENV:在容器中 设置环境变量,后续的 执行 RUN 指令的容器中就可以开始使用。ENV 设置的环境变量在 ADD、COPY、ENV、EXPOSE、FROM、LABEL、STOPSIGNAL、USER、VOLUME、WORKDIR、ONBUILD 等指令中可以使用(指令是在镜像容器中运行的,不能引用宿主机本地的环境变量)。

指令格式:

ENV <key>=<value> <key>=<value> <key>=<value> ...

指令示例:

ENV MY_NAME="John Doe"
ENV MY_DOG=Rex\ The\ Dog
ENV MY_CAT=fluffy

# 可以一次性设置多个
ENV MY_NAME="John Doe" \
    MY_DOG=Rex\ The\ Dog \
    MY_CAT=fluffy

ENV 设置的环境变量将持久性保存在镜像和容器中。如果需要在构建期间使用环境变量(不保存到镜像中),可以在 RUN 指令中设置会话级别的环境变量(RUN HEELO=world && echo $HELLO)或使用 ARG 指令。

6.6 ARG

ARG:定义一个变量(可以指定默认值),在执行 docker build 命令时可以传入参数给此变量赋值(--build-arg <ARG_NAME>=<value>),后续指令可以使用 ${ARG_NAME} 引用变量的值。与 ENV 不同,ARG 设置的变量不会保存到最终的镜像中,ARG 变量仅在构建过程中(包括在执行 RUN 指令的容器中)有效。

指令格式:

ARG <name>[=<default value>]

指令示例:

ARG from_linux=busybox
FROM ${from_linux}

ARG touch_workdir
WORKDIR ${touch_workdir}

ARG Hello=World
RUN touch "${Hello}.txt"

FROM 指令外的其他指令中使用 ARG 参数,需要在 FROM 指令之后定义。

构建:

# 构建镜像
$ docker build \
        --build-arg from_linux=alpine \
        --build-arg touch_workdir=/root \
        -t test_image \
        .
...

# 运行容器测试
$ docker run --rm -it test_image ls /root
World.txt

6.7 COPY

COPY:复制文件/文件夹到镜像的(新层)文件系统。

指令格式:

COPY [--chown=<user>:<group>] <src>... <dest>
COPY [--chown=<user>:<group>] ["<src>",... "<dest>"]

包含空格的路径需要使用第二种格式。可以指定添加进镜像后文件的拥有者([--chown=<user>:<group>])。<src> 表示宿主机本地的文件/文件夹目录,可以用有多个。最后一个为 <dest> 表示在容器中的文件/文件夹目录。

<src><dest> 可以是 绝对路径相对路径。如果为 相对路径,则 <src> 相对于 docker build [OPTIONS] PATH | URL | - 构建命令中的 PATH<dest> 相对于构建指令 WORKDIR 指定的目录(目录不存在会自动创建)。

指令示例:

# 宿主机本地的 {PATH}/aa.txt 和 {PATH}/bb.txt 文件 复制到 容器的 {WORKDIR}/abc/ 目录下
COPY aa.txt bb.txt abc/

# 宿主机本地的 {PATH}/aa.txt 复制到 {WORKDIR}/abc/ 目录下 并重命名为 bb.txt
COPY aa.txt abc/bb.txt

# 宿主机本地 aa_dir 文件夹下的所有内容(aa_dir/*) 复制到 容器的 /root/ 目录下
COPY aa_dir /root/

# 宿主机本地 aa_dir 文件夹 复制到 容器的 /root/ 目录下 并重命名为 bb_dir
COPY aa_dir /root/bb_dir

# 支持 * 和 ? 通配符
COPY hom?.txt /root/my_dir/
COPY *.jpg /root/my_dir/

6.8 ADD

ADD:添加文件/文件夹到镜像的(新层)文件系统(支持自动解压缩)。

指令格式:

ADD [--chown=<user>:<group>] <src>... <dest>
ADD [--chown=<user>:<group>] ["<src>",... "<dest>"]

ADD 指令添加文件时,如果 <src> 是可识别压缩格式 (identity、gzip、bzip2 或 xz) 的 tar 存档,则自动将其解压缩为目录,除此之外基本用法与 COPY 指令相同。

归档文件: test.tar.gz

test.tar.gz
|
|--- aa.txt
|
|--- bb_dir

指令示例:

# 添加后生成文件:
#   /root/aa.txt
#   /root/bb_dir
ADD test.tar.gz /root/

6.9 ENTRYPOINT

ENTRYPOINT:容器启动时执行的命令。有此参数时,CMD 指令的内容将作为 ENTRYPOINT 命令的参数。

ENTRYPOINT 有两种形式:

  • ENTRYPOINT ["executable", "param1", "param2"] (exec 形式,这是首选形式)
  • ENTRYPOINT command param1 param2 (sell 形式,命令将使用 /bin/sh -c "command param1 param2" 运行)

指令示例:

FROM ubuntu
ENTRYPOINT ["top", "-d", "1"]
CMD ["-n", "5"]

最终容器默认启动命令为:

$ exec top -d 1 -n 5

RUNCMD 指令的形式相同,exec 形式不会调用 shell 命令,也就是不会发生正常的外壳处理。例如,ENTRYPOINT ["echo", "$HOME"] 不会将 $HOME 替换为对应的环境变量值,而且直接使用字面值。要想 exec 形式运行命令并且进行 shell 处理,可以使用 exec 先运行一个 shell 再由 shell 运行命令,例如:ENTRYPOINT ["sh", "-c", "echo $HOME"],与 shell 形式一样,这里是 shell 进行环境变量扩展,而不是 docker。

6.9 EXPOSE

EXPOSE:创建容器时打算发布(暴露)的(TCP/UDP)端口。

指令格式:

EXPOSE <port> [<port>/<protocol>...]

EXPOSE 指令通知 Docker 容器在运行时打算监听的网络端口。可以指定端口监听 TCP 或 UDP 协议,如果不指定协议,则默认为 TCP。

EXPOSE 指令实际上并未发布/监听端口。它充当镜像的 构建者 和 使用者 之间的一种默契说明,告诉使用者使用容器时需要暴露的端口,还需要在运行容器(docker run/create)时使用 -p 参数真正地发布/映射端口。

指令示例:

EXPOSE 8000/udp 8080/tcp

# 还可以同时在一个端口同时暴露 TCP 和 UDP
EXPOSE 80/tcp 80/udp

6.11 VOLUME

VOLUME:创建容器时自动创建卷并挂载到指定挂载点。

指令格式:

VOLUME ["/data", "/aa/bb", ...]

指令示例:

FROM busybox

# 创建容器时将创建两个卷, 分别挂载到 /aa 和 /bb/cc
VOLUME ["/aa", "/bb/cc"]

构建运行:

# 构建镜像
$ docker build -t test_image .

# 创建容器
$ docker create test_image
...

# 查看自动生成的卷
$ docker volume ls
DRIVER    VOLUME NAME
local     210ec6...
local     f00eac...

# 运行容器 查看挂载点 (每次创建容器都会创建卷, 加 --rm 参数退出容器时卷将自动删除)
$ docker run --rm -it test_image df -h
Filesystem                Size      Used Available Use% Mounted on
overlay                  58.4G      2.9G     52.5G   5% /
tmpfs                    64.0M         0     64.0M   0% /dev
shm                      64.0M         0     64.0M   0% /dev/shm
/dev/vda1                58.4G      2.9G     52.5G   5% /aa
/dev/vda1                58.4G      2.9G     52.5G   5% /bb/cc
...

6.12 USER

USER:改变运行 RUN、CMD、ENTRYPOINT 等指令的用户身份,以及容器启动时默认的用户身份,用户必须是容器内已创建的。没有指定用户,默认为 root 用户。

指令格式:

USER <user|UID>[:<group:GID>]

指令示例:

FROM ubuntu

# 先创建用户
RUN useradd -m hello

# 使用 hello 用户身份
USER hello

# RUN 指令中输出当前用户名称: hello
RUN whoami

# 容器运行时输出当前用户名称: hello
CMD whoami

6.13 WORKDIR

WORKDIR:改变后面的指令运行时的工作目录(容器内目录,运行容器时的默认工作目录也是此目录),可以是相对路径(相对于上一条 WORKDIR 指令的路径),默认路径为 /

指令格式:

WORKDIR /path/to/workdir

路径如果不存在,会自动创建。提供的路径可以是 绝对路径 或 相对路径。如果是相对路径,则相对于上一条 WORKDIR 的路径。

指令示例:

FROM busybox

# 改变路径
WORKDIR /a/b

# 输出的路径为 /a/b
RUN pwd

# 输出的路径为 /a/b
CMD pwd

6.14 ONBUILD

ONBUILD:当此镜像被其他 Dockerfile 作为基础镜像被引用时触发的指令(如 RUNCOPY 等),当前 Dockerfile 构建时不执行,被其他 Dockerfile 引用时的 FROM 指令中执行。

指令格式:

ONBUILD <INSTRUCTION>

指令示例:

ONBUILD RUN cd /root && touch hello.txt
ONBUILD RUN /usr/local/bin/python-build --dir /app/src

6.15 SHELL

SHELL:覆盖用于运行命令时默认用的 shell,Linux 默认是 ["/bin/sh", "-c"],Windows 的默认是 ["cmd", "/S", "/C"]

SHELL 指令可以出现多次。每条 SHELL 指令都会覆盖前面的 SHELL 指令,并影响所有后续指令。

指令格式:

SHELL ["executable", "parameters"]

指令示例:

FROM ubuntu

# 使用 ["/bin/bash", "-c"] 作为默认 shell
SHELL ["/bin/bash", "-c"]

# 将被运行为: /bin/bash -c "ls -l"
RUN ls -l

# 将被运行为: /bin/bash -c "top"
CMD top 

6.16 STOPSIGNAL

STOPSIGNAL:设置将被发送到容器以退出容器的系统调用信号(容器停止信号),默认为 SIGTERM

指令格式:

STOPSIGNAL signal

可以在 docker run/create 运行容器时使用 --stop-signal 参数覆盖镜像中的默认停止信号。

6.17 HEALTHCHECK

HEALTHCHECK:容器健康检查指令,告诉 Docker 如何测试容器以检查它是否仍在工作。

HEALTHCHECK 指令的两种形式:

  • HEALTHCHECK [OPTIONS] CMD command (通过在容器内运行命令检查容器运行状况)
  • HEALTHCHECK NONE (禁用从基础镜像继承的任何运行状况检查)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

谢TS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值