Docker系列之二:常用命令解析


title: Docker系列之二:常用命令解析
categories: Docker
tags:
- Docker
timezone: Asia/Shanghai
date: 2019-02-01

版本

[root@localhost home]# docker --version
Docker version 18.09.0, build 4d60db4

快捷键

CTRL + p + q    退出一个容器,并保持容器继续运行
CTRL + d        退出一个容器,并终止容器的运行

目录:

docker run
docker build
docker images
docker image

docker search:在Docker Hub中搜索image

[root@centos181001 ~]# docker search --help
Usage:	docker search [OPTIONS] TERM
Search the Docker Hub for images
Options:
  -f, --filter filter   Filter output based on conditions provided
                        根据提供的条件过滤输出
      --format string   Pretty-print search using a Go template
                        格式化输出
      --limit int       Max number of search results (default 25)
                        最大搜索结果数(默认25)
      --no-trunc        Don't truncate output
                        不要截断输出

docker run

[root@centos181001 home]# 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
                                        指定标准输入输出内容类型,可选 STDIN/STDOUT/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
      --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
                                        后台运行容器,并返回容器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 8.8.8.8: 指定容器使用的DNS服务器,默认和宿主一致;

      --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
                                              -e username="ritchie": 设置环境变量;

      --env-file list                  Read in a file of environment variables
                                        --env-file=[]: 从指定文件读入环境变量;

      --expose list                    Expose a port or a range of ports
                                        --expose=[]: 开放一个端口或一组端口;

      --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
                                        -h "mars": 指定容器的hostname;

      --init                           Run an init inside the container that forwards signals and reaps processes
  -i, --interactive                    Keep STDIN open even if not attached
                                        以交互模式运行容器,通常与 -t 同时使用

      --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=[]: 添加链接到另一个容器;

      --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
                                        -m :设置容器使用内存最大值;

      --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
                                        --name="nginx-lb": 为容器指定一个名称;

      --network string                 Connect a container to a network (default "default")
      --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)
      --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
                                        将所有公开的端口发布到随机端口

      --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: [:])
      --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
  
示例:
运行一个docker并进入容器
docker run -it centos /bin/bash

运行一个docker,并保持后台运行,不进入容器
docker run -itd centos /bin/bash

运行一个容器并返回容器ID,同时保持后台运行不退出
docker run -d centos

运行一个容器,并在容器退出的时候自动删除
docker run -it --rm 9b65eb17913a

docker attach:进入到一个容器

[root@centos181001 ~]# docker attach --help
Usage:	docker attach [OPTIONS] CONTAINER
Attach local standard input, output, and error streams to a running container
Options:
      --detach-keys string   Override the key sequence for detaching a container
      --no-stdin             Do not attach STDIN
                            不要附上STDIN
      --sig-proxy            Proxy all received signals to the process (default true
                            代理所有收到的进程信号(默认为真)

docker container

[root@centos181001 ~]# docker container --help
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.

docker container attach(进入到一个容器)(等于docker attach)

docker container commit(根据容器的更改创建新image)(等于docker commit)

docker container cp(在容器和本地文件系统之间复制文件/文件夹)

[root@centos181001 ~]# docker container cp --help
Usage:	docker container cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
	docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH
Copy files/folders between a container and the local filesystem
Options:
  -a, --archive       Archive mode (copy all uid/gid information)
                        存档模式(复制所有uid / gid信息)
  -L, --follow-link   Always follow symbol link in SRC_PATH
                        始终遵循SRC_PATH中的符号链接

示例:

docker container start:启动一个或多个已停止的容器

[root@centos181001 ~]# docker container start --help
Usage:	docker container start [OPTIONS] CONTAINER [CONTAINER...]
Start one or more stopped containers
Options:
  -a, --attach               Attach STDOUT/STDERR and forward signals
                            连接STDOUT / STDERR并转发信号
      --detach-keys string   Override the key sequence for detaching a container
  -i, --interactive          Attach container's STDIN

示例:
docker container start

docker ps(列出容器)

[root@centos181001 ~]# docker ps --help
Usage:	docker ps [OPTIONS]
List containers
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)
                        显示最后创建的容器(包括所有状态)(默认为-1)
  -l, --latest          Show the latest created container (includes all states)               显示最新创建的容器(包括所有状态)
      --no-trunc        Don't truncate output
                        不要截断输出
  -q, --quiet           Only display numeric IDs
                        只显示CONTAINER ID
  -s, --size            Display total file sizes
                        显示容器总文件大小

docker commit:根据容器的更改创建新image

[root@centos181001 ~]# docker commit --help
Usage:	docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
Create a new image from a container's changes
Options:
  -a, --author string    Author (e.g., "John Hannibal Smith ")
                        作者信息
  -c, --change list      Apply Dockerfile instruction to the created image
                        
  -m, --message string   Commit message
                        提交信息
  -p, --pause            Pause container during commit (default true)
                        在提交期间暂停容器(默认为true)

示例:
docker commit 1ff50d9bf8af centos_vim:1.0

docker build:从Dockerfile构建映像(此命令等于:docker image build)

Usage:	docker build [OPTIONS] PATH | URL | -
    使用-构建:
        docker build - < Dockerfile
        docker build - < context.tar.gz
    
    URL参数可以引用三种类型的资源:Git仓库,预打包的tarball上下文和纯文本文件。

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
      --cgroup-parent string    Optional parent cgroup for the container
      --compress                Compress the build context using gzip
                                使用gzip压缩构建上下文

      --cpu-period int          Limit the CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int           Limit the CPU CFS (Completely Fair Scheduler) quota
  -c, --cpu-shares int          CPU shares (relative weight)
      --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)
      --disable-content-trust   Skip image verification (default true)
                                默认跳过对生成的image的测试,设置该选项,将对镜像进行验证

  -f, --file string             Name of the Dockerfile (Default is 'PATH/Dockerfile')
                                指定Dockerfile的路径,默认:'PATH/Dockerfile'

      --force-rm                Always remove intermediate containers
                                总是删除掉中间环节的容器

      --iidfile string          Write the image ID to the file
                                写入image ID到文件

      --isolation string        Container isolation technology
                                容器隔离技术

      --label list              Set metadata for an image
                                为生成的镜像设置metadata

  -m, --memory bytes            Memory limit
                                默认启动一个 container,对于容器的内存是没有任何限制的。
                                
      --memory-swap bytes       Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --network string          Set the networking mode for the RUN instructions during build (default "default")
      --no-cache                Do not use cache when building the image
                                构建image的时候不要使用缓存,默认false

      --pull                    Always attempt to pull a newer version of the image
                                在构建image的时候总是尝试pull镜像的最新版本

  -q, --quiet                   Suppress the build output and print image ID on success
      --rm                      Remove intermediate containers after a successful build (default true)
                                成功构建后删除中间容器(默认为true)

      --security-opt strings    Security options
                                安全选项

      --shm-size bytes          Size of /dev/shm
  -t, --tag list                Name and optionally a tag in the 'name:tag' format
      --target string           Set the target build stage to build.
      --ulimit ulimit           Ulimit options (default [])

示例:
使用当前目录的Dockerfile生成image并查看
docker build -t centos_tengine:1.0 .
docker image ls centos_tengine

docker images

此命令等于:docker image ls

docker image

[root@centos181001 home]# docker image push --help
Usage:	docker image push [OPTIONS] NAME[:TAG]
Push an image or a repository to a registry
Options:
      --disable-content-trust   Skip image signing (default true)
[root@centos181001 home]# docker image --help
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.

build:从Dockerfile构建映像(等同于docker build)

history:查看指定image的创建历史

Usage:	docker image history [OPTIONS] IMAGE
Show the history of an image
Options:
      --format string   Pretty-print images using a Go template
                        格式化输出
  -H, --human           Print sizes and dates in human readable format (default true)
                        以人类可读格式打印尺寸和日期(默认为true)
      --no-trunc        Don't truncate output
                        不要截断输出(长IMAGE ID格式)
  -q, --quiet           Only show numeric IDs
                        只显示IMAGE ID

示例:
docker image history httpd:latest
docker image history db7b8a965358
docker image history --no-trunc db7b8a965358
docker image history -q db7b8a965358

import:根据export出的tar文件创建一个镜像.

Usage:	docker image import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]
Import the contents from a tarball to create a filesystem image
Options:
  -c, --change list      Apply Dockerfile instruction to the created image
  -m, --message string   Set commit message for imported image

示例:
docker image import /home/nginx.tar nginx:latest
    这里需要指定新镜像的名字和标签,否则会显示

inspect:显示一个或多个image的详细信息

Usage:	docker image inspect [OPTIONS] IMAGE [IMAGE...]
Display detailed information on one or more images
Options:
  -f, --format string   Format the output using the given Go template
                        格式化输出
示例:
docker image inspect 42b4762643dc
docker image inspect nginx
docker image inspect nginx:latest
docker image inspect nginx:latest hello-world

load:从tar归档文件或者标准输入流载入iamge

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
                       从tar归档文件中读取,而不是STDIN
  -q, --quiet          Suppress the load outp

示例:
docker image load -i /home/nginx.tar

ls:列出image(此命令等于docker images)

Usage:	docker image ls [OPTIONS] [REPOSITORY[:TAG]]
List images
Aliases:
  ls, images, list
Options:
  -a, --all             Show all images (default hides intermediate images)
                        显示所有图像(默认隐藏中间图像)
      --digests         Show digests
                        显示摘要(可以显示镜像大小等信息)同时不要截断输出(显示长IMAGE ID格式)
  -f, --filter filter   Filter output based on conditions provided
                        根据提供的条件过滤输出
      --format string   Pretty-print images using a Go template
                        格式化输出
      --no-trunc        Don't truncate output
                        不要截断输出(显示长IMAGE ID格式)
  -q, --quiet           Only show numeric IDs
                        仅显示IMAGE ID
示例:
docker image ls nginx
docker image ls
docker image ls -a
docker image ls --digests
docker image ls --no-trunc
docker image ls -q

prune:删除未使用的image

Usage:	docker image prune [OPTIONS]
Remove unused images
默认情况下,只会清理 dangling 镜像。
悬挂镜像是一种特殊的镜像,这种镜像既没有仓库名也没有标签,他们的值都为
一般来说,虚悬镜像已经失去了存在的价值,是可以随意删除的
dangling经常可以用以下命令查看:docker image ls -f dangling=true

Options:
  -a, --all             Remove all unused images, not just dangling ones
                        通过 -a 标志可以删除没有被已有容器使用的所有镜像:而不只是删除悬空镜像
      --filter filter   Provide filter values (e.g. 'until=')
                        提供过滤器
                        
  -f, --force           Do not prompt for confirmation
                        强制删除,不提示确认
示例:
docker image prune
docker image prune -a
docker image prune -a -f

pull:拉取镜像

Usage:	docker image pull [OPTIONS] NAME[:TAG|@DIGEST]
Options:
  -a, --all-tags                Download all tagged images in the repository
      --disable-content-trust   Skip image verification (default true)
                                拉取所有版本

示例:
docker image pull nginx
docker image pull -a nginx

push:推送iamge到仓库

Usage:	docker image push [OPTIONS] NAME[:TAG]
Options:跳过图像签名
  --disable-content-trust   Skip image signing (default true)

示例:
docker image push hello-world:1.0

rm:删除一个或多个image

Usage:	docker image rm [OPTIONS] IMAGE [IMAGE...]
Aliases:
  rm, rmi, remove

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

示例:
docker image rm hello-world:2.0 hello-world:latest

save:将一个或多个图像保存到tar存档(默认情况下流式传输到STDOUT)

Usage:	docker save [OPTIONS] IMAGE [IMAGE...]
Options:
        -o, --output string   Write to a file, instead of STDOUT

示例:
docker save -o /home/hello-world.tar hello-world
docker save -o /home/hello-world.tar hello-world:2.0
docker save -o /home/hello-world.tar fce289e99eb9

tag:为image打标签

Usage:	docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]

示例:
docker image tag hello-world hello-world:2.0

你可能感兴趣的:(Docker)