`
剑锋凛冽
  • 浏览: 73182 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

docker命令行翻译

 
阅读更多

Docker命令行

Docker命令使用

英文原版地址:https://docs.docker.com/reference/commandline/cli

PS:翻译过程中,某些术语(如image)没有翻译,相应的中文含义不太一致,所以保留了英文。

PS:docker命令要求root权限,最好切换到root用户执行。 
要获得可用的docker命令,使用无参数的docker命令或者执行docker help:

$ sudo docker
  Usage: docker [OPTIONS] COMMAND [arg...]
    -H, --host=[]: The socket(s) to bind to in daemon mode, specified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd.

  A self-sufficient runtime for linux containers.

  ...
 

选项类型

单个字母的命令行选项可以合并。 
eg: docker run -t -i --name test busybox sh
等价于 docker run -ti --name test busybox sh.

 

Boolean

Boolean类型的选项,eg,-d=false. 此例子中的值为不使用此选项时的默认值。 使用-d时,将使选项值置为true.例如,如果调用 run -d, 将选项-d设置为 true,所以docker run -d命令将使容器运行于"detached模式",并且保持在后台. 其他Boolean类型的选项与此类似,指定该选项时,将使选项值设置为默认值的相反值。

 

Multi

-a=[]这种类型的选项可以多次设值。eg:

$ sudo docker run -a stdin -a stdout -a stderr -i -t ubuntu /bin/bash

有时,也可以使用另外一种更复杂的空格分隔的多选项值字符串方式。eg,-v选项的使用:

$ sudo docker run -v /host:/container example/mysql
 

Strings and Integers

--name=""等类似的选项,表示选项值为字符串,而且只能设一次值。 -c=0等类似选项,表示选项值为整数,而且只能设一次值。

 

docker守护进程

Usage: docker [OPTIONS] COMMAND [arg...]

A self-sufficient runtime for linux containers.

Options:
  --api-enable-cors=false                    Enable CORS headers in the remote API
  -b, --bridge=""                            Attach containers to a pre-existing network bridge
                                               use 'none' to disable container networking
  --bip=""                                   Use this CIDR notation address for the network bridge's IP, not compatible with -b
  -D, --debug=false                          Enable debug mode
  -d, --daemon=false                         Enable daemon mode
  --dns=[]                                   Force Docker to use specific DNS servers
  --dns-search=[]                            Force Docker to use specific DNS search domains
  -e, --exec-driver="native"                 Force the Docker runtime to use a specific exec driver
  --fixed-cidr=""                            IPv4 subnet for fixed IPs (ex: 10.20.0.0/16)
                                               this subnet must be nested in the bridge subnet (which is defined by -b or --bip)
  -G, --group="docker"                       Group to assign the unix socket specified by -H when running in daemon mode
                                               use '' (the empty string) to disable setting of a group
  -g, --graph="/var/lib/docker"              Path to use as the root of the Docker runtime
  -H, --host=[]                              The socket(s) to bind to in daemon mode or connect to in client mode, specified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd.
  --icc=true                                 Enable inter-container communication
  --ip=0.0.0.0                               Default IP address to use when binding container ports
  --ip-forward=true                          Enable net.ipv4.ip_forward
  --ip-masq=true                             Enable IP masquerading for bridge's IP range
  --iptables=true                            Enable Docker's addition of iptables rules
  --mtu=0                                    Set the containers network MTU
                                               if no value is provided: default to the default route MTU or 1500 if no default route is available
  -p, --pidfile="/var/run/docker.pid"        Path to use for daemon PID file
  --registry-mirror=[]                       Specify a preferred Docker registry mirror
  -s, --storage-driver=""                    Force the Docker runtime to use a specific storage driver
  --selinux-enabled=false                    Enable selinux support. SELinux does not presently support the BTRFS storage driver
  --storage-opt=[]                           Set storage driver options
  --tls=false                                Use TLS; implied by tls-verify flags
  --tlscacert="/home/sven/.docker/ca.pem"    Trust only remotes providing a certificate signed by the CA given here
  --tlscert="/home/sven/.docker/cert.pem"    Path to TLS certificate file
  --tlskey="/home/sven/.docker/key.pem"      Path to TLS key file
  --tlsverify=false                          Use TLS and verify the remote (daemon: verify client, client: verify daemon)
  -v, --version=false                        Print version information and quit

docker守护进程是用于管理容器的后台进程。守护进程和客户端使用相同的二进制发布包。 
要运行守护进程,使用-d选项。 
使用守护进程时,必须先保证docker客户端停止,二者不允许同时使用,否则,将导致无法运行。

如果要强制docker使用devicemapper作为存储驱动,使用如下命令: 
docker -d -s devicemapper
如果要为所有的docker容器设置DNS服务器,使用如下命令: 
docker -d --dns 8.8.8.8
如果要为所有的docker容器设置DNS查询域(dns search domain),使用如下命令: 
docker -d --dns-search example.com.

如果要使docker守护进程输出debug信息, 使用如下命令: 
docker -d -D.

如果要使用lxc作为执行驱动(操纵容器时使用),使用如下命令: 
docker -d -e lxc.

docker客户端使用环境变量DOCKER_HOST,作为客户端的-H选项的值。

$ sudo docker -H tcp://0.0.0.0:2375 ps

或者

$ export DOCKER_HOST="tcp://0.0.0.0:2375"
$ sudo docker ps

以上两种方式是等价的。

IP伪装(masquerading)使用地址转发功能,使容器在不使用公有IP的情况下与网络上的其他机器通信。 它有可能会干扰网络拓扑,可以使用--ip-masq=false选项来禁止这个功能。

要使docker与 [systemd socket activation]( 
http://0pointer.de/blog/projects/socket-activation.html)结合使用, 使用如下命令: 
docker -d -H fd://
使用 fd://可以在大多数配置下工作。 
当然,你也可以用 docker -d -H fd://3来指定特定套接字.如果指定的套接字激活文件(socket activated files)不存在,docker守护进程将自动退出。 
可以参考[docker source tree]( 
https://github.com/docker/docker/tree/master/contrib/init/systemd/).来联合使用docker和systemd socket activation。

docker支持数据文件夹的软连接,包括 
(/var/lib/docker) 和/var/lib/docker/tmp两个目录. DOCKER_TMPDIR和docker数据文件可以使用如下方式进行设置:

DOCKER_TMPDIR=/mnt/disk2/tmp /usr/local/bin/docker -d -D -g /var/lib/docker -H unix:// > /var/lib/boot2docker/docker.log 2>&1

或者

export DOCKER_TMPDIR=/mnt/disk2/tmp
/usr/local/bin/docker -d -D -g /var/lib/docker -H unix:// > /var/lib/boot2docker/docker.log 2>&1
 

attach命令

Usage: docker attach [OPTIONS] CONTAINER

连接到已运行的容器中。

  --no-stdin=false    Do not attach STDIN
  --sig-proxy=true    Proxy all received signals to the process (even in non-TTY mode). SIGCHLD, SIGKILL, and SIGSTOP are not proxied.

attach命令使你能够查看任何已运行容器,或者与任何已运行的容器进行交互。要求相应容器为detached模式(通过-d选项启动),或者交互模式(通过-i选项启动)。允许同时挂载在同一个容器中--以共享方式实现交互。 
使用CTRL-p CTRL-q退出容器,并使容器保持运行。 
使用CTRL-cCTRL-d退出容器,将向容器发送SIGKILL,导致容器停止。使用 CTRL-\退出容器时,将会输出docker客户端的堆栈信息。

退出容器时,exit code将会返回给docker客户端。

如果要关闭一个容器,使用命令 
docker stop.

如果要杀死一个容器,使用命令 
docker kill.

 

例子

$ ID=$(sudo docker run -d ubuntu /usr/bin/top -b)
$ sudo docker attach $ID
top - 02:05:52 up  3:05,  0 users,  load average: 0.01, 0.02, 0.05
Tasks:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.1%us,  0.2%sy,  0.0%ni, 99.7%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:    373572k total,   355560k used,    18012k free,    27872k buffers
Swap:   786428k total,        0k used,   786428k free,   221740k cached

PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 1 root      20   0 17200 1116  912 R    0  0.3   0:00.03 top

 top - 02:05:55 up  3:05,  0 users,  load average: 0.01, 0.02, 0.05
 Tasks:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
 Cpu(s):  0.0%us,  0.2%sy,  0.0%ni, 99.8%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
 Mem:    373572k total,   355244k used,    18328k free,    27872k buffers
 Swap:   786428k total,        0k used,   786428k free,   221776k cached

   PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
       1 root      20   0 17208 1144  932 R    0  0.3   0:00.03 top


 top - 02:05:58 up  3:06,  0 users,  load average: 0.01, 0.02, 0.05
 Tasks:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
 Cpu(s):  0.2%us,  0.3%sy,  0.0%ni, 99.5%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
 Mem:    373572k total,   355780k used,    17792k free,    27880k buffers
 Swap:   786428k total,        0k used,   786428k free,   221776k cached

 PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
      1 root      20   0 17208 1144  932 R    0  0.3   0:00.03 top
^C$
$ sudo docker stop $ID
 

build命令

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

使用PATH指定的源代码去构建一个image。

  --force-rm=false     Always remove intermediate containers, even after unsuccessful builds
  --no-cache=false     Do not use cache when building the image
  -q, --quiet=false    Suppress the verbose output generated by the containers
  --rm=true            Remove intermediate containers after a successful build
  -t, --tag=""         Repository name (and optionally a tag) to be applied to the resulting image in case of success

使用build命令从Dockfile格式的文件或者上下文中构造Docker的image。 
PATHURL中的文件被称为构造的“上下文” 。构造过程中,有可能会引用上下文中的任意文件。例如,当使用 
ADD 指令时的情况。 
当通过URL或者标准输入 STDIN 
(docker build - < Dockerfile)的管道指定单个Dockerfile时,没有上下文设置。

当 URL指定的是Git仓库时,此仓库将作为构造image的上下文context. 这个Git仓库将会和它的子模块一起克隆 
(即git clone -recursive).此时,在你本机的临时目录中,将会通过 git clone 生成克隆,并作为Docker守护进程的上下文。通过这种方式,你可以在本地使用用户认证信息或VPN等手段,访问私有仓库。 
如果PATH指定的根路径中存在名为.dockerignore的文件,它将会被解析为一行逗号风格的exclusion表达式。PATH文件夹下,符合这个表达式的文件或目录,将不会用于构造上下文中。通配符采用Go语言的filepath.Match规则。 
注意:子目录中的.dockerignore 将会被视为正常文件。.dockerignore文件中的文件路径是相对于PATH指定的路径的绝对路径,文件路径中允许使用通配符,但搜索文件不会递归地搜索子目录。

 

.dockerignore文件内容示例

*/temp*
*/*/temp*
temp?

上面的第一行 */temp*,将忽略所有当前root目录下的所有子目录中以temp开头的 的文件。eg:文件 
/somedir/temporary.txt 将被忽略。第二行*/*/temp*,将忽略当前root目录下二级子目录中的所有temp开头的文件。 eg: /somedir/subdir/temporary.txt将会在这种情况下被忽略。 
最后一行 temp?,将忽略当前root目录中符合条件的文件。eg: 
当前root目录中的tempatempb文件将被忽略。 
目前,.dockerignore文件内容不支持正则表达式,所以[^temp*]这种格式的字符串将会被忽略。

可以参考: 
Dockerfile Reference.

 

例子

$ sudo docker build .
Uploading context 10240 bytes
Step 1 : FROM busybox
Pulling repository busybox
 ---> e9aa60c60128MB/2.284 MB (100%) endpoint: https://cdn-registry-1.docker.io/v1/
Step 2 : RUN ls -lh /
 ---> Running in 9c9e81692ae9
total 24
drwxr-xr-x    2 root     root        4.0K Mar 12  2013 bin
drwxr-xr-x    5 root     root        4.0K Oct 19 00:19 dev
drwxr-xr-x    2 root     root        4.0K Oct 19 00:19 etc
drwxr-xr-x    2 root     root        4.0K Nov 15 23:34 lib
lrwxrwxrwx    1 root     root           3 Mar 12  2013 lib64 -> lib
dr-xr-xr-x  116 root     root           0 Nov 15 23:34 proc
lrwxrwxrwx    1 root     root           3 Mar 12  2013 sbin -> bin
dr-xr-xr-x   13 root     root           0 Nov 15 23:34 sys
drwxr-xr-x    2 root     root        4.0K Mar 12  2013 tmp
drwxr-xr-x    2 root     root        4.0K Nov 15 23:34 usr
 ---> b35f4035db3f
Step 3 : CMD echo Hello world
 ---> Running in 02071fceb21b
 ---> f52f38b7823e
Successfully built f52f38b7823e
Removing intermediate container 9c9e81692ae9
Removing intermediate container 02071fceb21b

这个例子中,PATH指定的是当前目录 
.,所以当前目录下的所有文件都会被 
打包然后发送给docker守护进程。PATH为docker守护进程指定了构造image时的上下文中的文件路径。注意守护进程可以在远程及其上执行,而且客户端(运行docker build的机器)不会对Dockerfile进行任何解析。因此,PATH中的所有文件都会被发送给docker守护进程,而不仅仅是Dockerfile中 
ADD中指定的文件。 
本地机器传输上下文给Docker守护进程的过程中,本地机器上的docker客户端将显示"Sending build context"消息。 
如果你希望保留构造image过程中产生的中间容器,必须使用--rm=false选项. 它不会影响构造过程中的缓存。

$ sudo docker build .
Uploading context 18.829 MB
Uploading context
Step 0 : FROM busybox
 ---> 769b9341d937
Step 1 : CMD echo Hello world
 ---> Using cache
 ---> 99cc1ad10469
Successfully built 99cc1ad10469
$ echo ".git" > .dockerignore
$ sudo docker build .
Uploading context  6.76 MB
Uploading context
Step 0 : FROM busybox
 ---> 769b9341d937
Step 1 : CMD echo Hello world
 ---> Using cache
 ---> 99cc1ad10469
Successfully built 99cc1ad10469

这个例子中,使用.dockerignore来忽略上下文中的.git目录。其效果可以从上传的上下文大小中看出。

$ sudo docker build -t vieux/apache:2.0 .

这个例子中,构造出的image将会被打上tag,image的仓库名是vieux/apache,而且标签为2.0

$ sudo docker build - < Dockerfile

这个例子中,将从无上下文STDIN中读取一个文件. 因为没有上下文,本地目录中的内容不会发送给docker守护进程。 
因为上下文环境的要求,只有在使用URL``指定远端目录时,Dockerfile中的ADD`才可以工作。

$ sudo docker build - < context.tar.gz

这个例子中,将通过STDIN从压缩文件中读取上下文。支持的压缩文件格式有: bzip2, gzip and xz.

$ sudo docker build github.com/creack/docker-firefox

这个例子中,从GitHub的仓库中克隆,并使用克隆的仓库作为上下文,仓库根目录中的Dockerfile将作为构造过程中的Dockerfile。注意,你可以使用git://协议指定任意Git仓库。

注意: 如果上传的上下文中,没有任何文件或目录,docker build将返回no such file or directory错误。这个错误在没有上下文或者指定的文件在主机的其他路径上时,将会发生。 
出于安全考虑及保证远程docker机器可重复构造的原因,上下文只能是当前目录及其子目录,这也是为什么ADD ../file不工作的原因。

 

commit命令

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

使用容器的修改生成一个新的image。
  -a, --author=""     Author (e.g., "John Hannibal Smith <hannibal@a-team.com>")
  -m, --message=""    Commit message
  -p, --pause=true    Pause container during commit

这个命令在提交容器的文件变更或者设置成一个新image时很有用。它允许你通过交互性shell与已运行的容器进行debug,或者把现有工作环境导出到另外的机器上。通常情况下,使用Dockerfile来管理image在文档化和可维护性上更好。 
默认情况下,正在提交的容器机器进程将处于paused状态。这种方式,避免了提交image过程中的数据变化。如果提交时不需要暂停容器,将p选项置为false即可。

 

提交已有容器

$ sudo docker ps
ID                  IMAGE               COMMAND             CREATED             STATUS              PORTS
c3f279d17e0a        ubuntu:12.04        /bin/bash           7 days ago          Up 25 hours
197387f1b436        ubuntu:12.04        /bin/bash           7 days ago          Up 25 hours
$ sudo docker commit c3f279d17e0a  SvenDowideit/testimage:version3
f5283438590d
$ sudo docker images | head
REPOSITORY                        TAG                 ID                  CREATED             VIRTUAL SIZE
SvenDowideit/testimage            version3            f5283438590d        16 seconds ago      335.7 MB
 

cp

复制重启中的文件系统中的文件或文件夹到容器宿主机上的指定目录。 
路径格式为相对容器的根目录。

Usage: docker cp CONTAINER:PATH HOSTPATH

Copy files/folders from the PATH to the HOSTPATH
 

create命令(1.2版本不支持)

创建一个新容器。

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

Create a new container

  -a, --attach=[]            Attach to STDIN, STDOUT or STDERR.
  --add-host=[]              Add a custom host-to-IP mapping (host:ip)
  -c, --cpu-shares=0         CPU shares (relative weight)
  --cap-add=[]               Add Linux capabilities
  --cap-drop=[]              Drop Linux capabilities
  --cidfile=""               Write the container ID to the file
  --cpuset=""                CPUs in which to allow execution (0-3, 0,1)
  --device=[]                Add a host device to the container (e.g. --device=/dev/sdc:/dev/xvdc)
  --dns=[]                   Set custom DNS servers
  --dns-search=[]            Set custom DNS search domains
  -e, --env=[]               Set environment variables
  --entrypoint=""            Overwrite the default ENTRYPOINT of the image
  --env-file=[]              Read in a line delimited file of environment variables
  --expose=[]                Expose a port from the container without publishing it to your host
  -h, --hostname=""          Container host name
  -i, --interactive=false    Keep STDIN open even if not attached
  --link=[]                  Add link to another container in the form of name:alias
  --lxc-conf=[]              (lxc exec-driver only) Add custom lxc options --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1"
  -m, --memory=""            Memory limit (format: <number><optional unit>, where unit = b, k, m or g)
  --name=""                  Assign a name to the container
  --net="bridge"             Set the Network mode for the container
                               'bridge': creates a new network stack for the container on the docker bridge
                               'none': no networking for this container
                               'container:<name|id>': reuses another container network stack
                               'host': use the host network stack inside the container.  Note: the host mode gives the container full access to local system services such as D-bus and is therefore considered insecure.
  -P, --publish-all=false    Publish all exposed ports to the host interfaces
  -p, --publish=[]           Publish a container's port to the host
                               format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort
                               (use 'docker port' to see the actual mapping)
  --privileged=false         Give extended privileges to this container
  --restart=""               Restart policy to apply when a container exits (no, on-failure[:max-retry], always)
  -t, --tty=false            Allocate a pseudo-TTY
  -u, --user=""              Username or UID
  -v, --volume=[]            Bind mount a volume (e.g., from the host: -v /host:/container, from Docker: -v /container)
  --volumes-from=[]          Mount volumes from the specified container(s)
  -w, --workdir=""           Working directory inside the container

docker create命令在指定image上创建一个可读写的容器层,并且为特定命令的指定准备好了环境。生成的容器ID将通过STDOUT输出。 
类似于docker run -d,但docker create命令不会启动容器。你可以用docker start <container_id> 命令在任何使用启动生成的容器。 
它可以在你使用之前,先准备好环境。

 

使用示例

$ sudo docker create -t -i fedora bash
6d8af538ec541dd581ebc2a24153a28329acb5268abe5ef868c1f1a261221752
$ sudo docker start -a -i 6d8af538ec5
bash-4.2#
 

diff命令

列出容器文件系统中改变过的文件或者目录。

Usage: docker diff CONTAINER

Inspect changes on a container's filesystem

diff命令将会列出以下三种变更:

  1. A - Add
  2. D - Delete
  3. C - Change

For example:

$ sudo docker diff 7bb0e258aefe

C /dev
A /dev/kmsg
C /etc
A /etc/mtab
A /go
A /go/src
A /go/src/github.com
A /go/src/github.com/docker
A /go/src/github.com/docker/docker
A /go/src/github.com/docker/docker/.git
....
 

events命令

Usage: docker events [OPTIONS]

Get real time events from the server

  --since=""         Show all events created since timestamp
  --until=""         Stream events until this timestamp

容器将会报告下列事件:

create, destroy, die, export, kill, pause, restart, start, stop, unpause

image将报告下列事件:

untag, delete
 

示例

在这里例子中,你需要打开两个shell

Shell 1: 监听事件:

$ sudo docker events

Shell 2: 启动和关闭容器:

$ sudo docker start 4386fb97867d
$ sudo docker stop 4386fb97867d

Shell 1: 输出事件内容:

2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from 12de384bfb10) start
2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from 12de384bfb10) die
2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from 12de384bfb10) stop

显示过去某个时间之后的事件:

$ sudo docker events --since 1378216169
2014-03-10T17:42:14.999999999Z07:00 4386fb97867d: (from 12de384bfb10) die
2014-03-10T17:42:14.999999999Z07:00 4386fb97867d: (from 12de384bfb10) stop

$ sudo docker events --since '2013-09-03'
2014-09-03T17:42:14.999999999Z07:00 4386fb97867d: (from 12de384bfb10) start
2014-09-03T17:42:14.999999999Z07:00 4386fb97867d: (from 12de384bfb10) die
2014-09-03T17:42:14.999999999Z07:00 4386fb97867d: (from 12de384bfb10) stop

$ sudo docker events --since '2013-09-03 15:49:29 +0200 CEST'
2014-09-03T15:49:29.999999999Z07:00 4386fb97867d: (from 12de384bfb10) die
2014-09-03T15:49:29.999999999Z07:00 4386fb97867d: (from 12de384bfb10) stop
 

exec命令(1.2版本中没有此命令)

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

Run a command in an existing container

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

docker exec命令在已运行的容器中执行新的命令。 
一般,docker execdocker rundocker start之后执行。

 

示例

$ sudo docker run --name ubuntu_bash --rm -i -t ubuntu bash

上述命令将创建一个名为ubuntu_bash的容器,并启动一个Bash会话。

$ sudo docker exec -d ubuntu_bash touch /tmp/execWorks

上述命令将在已运行的容器ubuntu_bash中创建文件/tmp/execWorks.

$ sudo docker exec ubuntu_bash -it bash

此命令将会在已运行的容器 ubuntu_bash中开一个新的Bash会话。

 

export命令

Usage: docker export CONTAINER

Export the contents of a filesystem as a tar archive to STDOUT

例如:

$ sudo docker export red_panda > latest.tar

把名为red_panda上导出为lastest.tar压缩包。

 

history命令

Usage: docker history [OPTIONS] IMAGE

Show the history of an image

  --no-trunc=false     Don't truncate output
  -q, --quiet=false    Only show numeric IDs

为了查看docker:latest这个image是如何创建的,执行如下命令:

$ sudo docker history docker
IMAGE                                                              CREATED             CREATED BY                                                                                                                                                 SIZE
3e23a5875458790b7a806f95f7ec0d0b2a5c1659bfc899c89f939f6d5b8f7094   8 days ago          /bin/sh -c #(nop) ENV LC_ALL=C.UTF-8                                                                                                                       0 B
8578938dd17054dce7993d21de79e96a037400e8d28e15e7290fea4f65128a36   8 days ago          /bin/sh -c dpkg-reconfigure locales &&    locale-gen C.UTF-8 &&    /usr/sbin/update-locale LANG=C.UTF-8                                                    1.245 MB
be51b77efb42f67a5e96437b3e102f81e0a1399038f77bf28cea0ed23a65cf60   8 days ago          /bin/sh -c apt-get update && apt-get install -y    git    libxml2-dev    python    build-essential    make    gcc    python-dev    locales    python-pip   338.3 MB
4b137612be55ca69776c7f30c2d2dd0aa2e7d72059820abf3e25b629f887a084   6 weeks ago         /bin/sh -c #(nop) ADD jessie.tar.xz in /                                                                                                                   121 MB
750d58736b4b6cc0f9a9abe8f258cef269e3e9dceced1146503522be9f985ada   6 weeks ago         /bin/sh -c #(nop) MAINTAINER Tianon Gravi <admwiggin@gmail.com> - mkimage-debootstrap.sh -t jessie.tar.xz jessie http://http.debian.net/debian             0 B
511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158   9 months ago                                                                                                                                                                   0 B
 

images

Usage: docker images [OPTIONS] [NAME]

List images

  -a, --all=false      Show all images (by default filter out the intermediate image layers)
  -f, --filter=[]      Provide filter values (i.e. 'dangling=true')
  --no-trunc=false     Don't truncate output
  -q, --quiet=false    Only show numeric IDs

默认的docker images命令将列举出所有的顶级image、相应的仓库名和标签及虚拟大小。

docker的image使用中间层来提高复用性,降低磁盘使用并通过把docker build的每一步缓存起来加速构造image的过程。默认情况下,这个中间层不会被显示出来。

 

列举最近创建的image

$ sudo docker images | head
REPOSITORY                    TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
<none>                        <none>              77af4d6b9913        19 hours ago        1.089 GB
committest                    latest              b6fa739cedf5        19 hours ago        1.089 GB
<none>                        <none>              78a85c484f71        19 hours ago        1.089 GB
docker                        latest              30557a29d5ab        20 hours ago        1.089 GB
<none>                        <none>              0124422dd9f9        20 hours ago        1.089 GB
<none>                        <none>              18ad6fad3402        22 hours ago        1.082 GB
<none>                        <none>              f9f1e26352f0        23 hours ago        1.089 GB
tryout                        latest              2629d1fa0b81        23 hours ago        131.5 MB
<none>                        <none>              5ed6274db6ce        24 hours ago        1.089 GB
 

列出image的完整ID

$ sudo docker images --no-trunc | head
REPOSITORY                    TAG                 IMAGE ID                                                           CREATED             VIRTUAL SIZE
<none>                        <none>              77af4d6b9913e693e8d0b4b294fa62ade6054e6b2f1ffb617ac955dd63fb0182   19 hours ago        1.089 GB
committest                    latest              b6fa739cedf5ea12a620a439402b6004d057da800f91c7524b5086a5e4749c9f   19 hours ago        1.089 GB
<none>                        <none>              78a85c484f71509adeaace20e72e941f6bdd2b25b4c75da8693efd9f61a37921   19 hours ago        1.089 GB
docker                        latest              30557a29d5abc51e5f1d5b472e79b7e296f595abcf19fe6b9199dbbc809c6ff4   20 hours ago        1.089 GB
<none>                        <none>              0124422dd9f9cf7ef15c0617cda3931ee68346455441d66ab8bdc5b05e9fdce5   20 hours ago        1.089 GB
<none>                        <none>              18ad6fad340262ac2a636efd98a6d1f0ea775ae3d45240d3418466495a19a81b   22 hours ago        1.082 GB
<none>                        <none>              f9f1e26352f0a3ba6a0ff68167559f64f3e21ff7ada60366e2d44a04befd1d3a   23 hours ago        1.089 GB
tryout                        latest              2629d1fa0b81b222fca63371ca16cbf6a0772d07759ff80e8d1369b926940074   23 hours ago        131.5 MB
<none>                        <none>              5ed6274db6ceb2397844896966ea239290555e74ef307030ebb01ff91b1914df   24 hours ago        1.089 GB
 

列举时过滤image

过滤器标签 (-f or --filter)格式为"key=value"。如果有多个过滤器,多次为过滤器标签设值即可。(e.g., --filter "foo=bar" --filter "bif=baz")

现有过滤器标签: 
* dangling (标记image是否有TAG,布尔值 - true或false)

 
列举没有TAG的images
$ sudo docker images --filter "dangling=true"

REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
<none>              <none>              8abc22fbb042        4 weeks ago         0 B
<none>              <none>              48e5f45168b9        4 weeks ago         2.489 MB
<none>              <none>              bf747efa0e2f        4 weeks ago         0 B
<none>              <none>              980fe10e5736        12 weeks ago        101.4 MB
<none>              <none>              dea752e4e117        12 weeks ago        101.4 MB
<none>              <none>              511136ea3c5a        8 months ago        0 B

上述命令将显示没有TAG的image,也就是image树(非中间层)的叶子节点。 
这些image会在构造新的image时,把repo:tag从image中删除掉后出现. 如果现有容器正在使用image,删除此image时,将会出现警告信息。 
如果要批量清理没有TAG的image,用如下方式调用docker rmi ...命令:

$ sudo docker rmi $(sudo docker images -f "dangling=true" -q)

8abc22fbb042
48e5f45168b9
bf747efa0e2f
980fe10e5736
dea752e4e117
511136ea3c5a

NOTE: 如果容器使用了无TAG的image,Docker将会进行警告。

 

import

Usage: docker import URL|- [REPOSITORY[:TAG]]

创建一个空文件系统的image,并把压缩包(支持格式.tar, .tar.gz, .tgz, .bzip, .tar.xz, .txz)的内容导入到image中。可以选择同时给这个image加上标签。
如果是`URL`,只支持`HTTP`协议,并且路径指向一个单一的文件压缩包 (支持格式.tar,

.tar.gz, .tgz, .bzip, .tar.xz, or .txz) 。如果要从本地文件夹或者压缩包中导入image,使用-参数从STDIN中去读文件。.

 

示例

从远端压缩包创建一个无标签image:

此命令将创建出一个没有标签的新image.

$ sudo docker import http://example.com/exampleimage.tgz

从本地文件创建一个新的image: 
通过管道和STDIN标准输入流创建新的image。

$ cat exampleimage.tgz | sudo docker import - exampleimagelocal:new

从本地目录中创建新的image:

$ sudo tar -c . | sudo docker import - exampleimagedir

注意这个例子中的sudo–必须保证创建压缩包过程中的文件的属主权限不变(特别是root属主权限)。 如果你是非root用户并且没有通过sudo创建压缩包,文件的属主权限可能无法保持。

 

info

Usage: docker info

Display system-wide information

例如:

$ sudo docker -D info
Containers: 14
Images: 52
Storage Driver: btrfs
Execution Driver: native-0.2
Kernel Version: 3.13.0-24-generic
Operating System: Ubuntu 14.04 LTS
Debug mode (server): false
Debug mode (client): true
Fds: 10
Goroutines: 9
EventsListeners: 0
Init Path: /usr/bin/docker
Username: svendowideit
Registry: [https://index.docker.io/v1/]

全局通用选项-D,可以使所有docker命令输出debug信息。 
如果要向docker官方报告问题,使用docker versiondocker -D info 命令告知你的配置是什么。

 

inspect

Usage: docker inspect [OPTIONS] CONTAINER|IMAGE [CONTAINER|IMAGE...]

Return low-level information on a container or image

  -f, --format=""    Format the output using the given go template.

返回容器或image的低级信息。默认情况下,inspect命令的输出为JSON数组。如果指定了其他格式,相应模板会被应用于结果中。 
Go语言的 text/template描述了格式的各种细节。

 

示例

获得容器的IP地址:

大多数情况下,你可以直接用JSON方式获取结果的值,eg:

$ sudo docker inspect --format='{{.NetworkSettings.IPAddress}}' $CONTAINER_ID

查看所有的端口绑定:

你可以对结果中的数组和map进行迭代,来产生简单的文本输出,例如:

$ sudo docker inspect --format='{{range $p, $conf := .NetworkSettings.Ports}} {{$p}} -> {{(index $conf 0).HostPort}} {{end}}' $CONTAINER_ID

找到特定的端口映射:

.Field语法对名字以数字开头的字段无效,但是模板语言的index 函数是有效的. .NetworkSettings.Ports部分包含和内部端口与外部端口映射的map,所以为了获得相应共有端口的映射,使用index找到相应的端口映射,index 0包含了第一个对象的值。然后我们就可以取HostPort字段的值来获取公有IP,如下所示:

$ sudo docker inspect --format='{{(index (index .NetworkSettings.Ports "8787/tcp") 0).HostPort}}' $CONTAINER_ID

获得配置:

.Field语法在字段包含JSON数据时无效,但模板语言中json函数是有效的. .config部分包含了复杂的JSON对象。为了把配置获取为JSON对象,使用json函数把配置转换为JSON对象。

$ sudo docker inspect --format='{{json .config}}' $CONTAINER_ID
 

kill

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

Kill a running container using SIGKILL or a specified signal

  -s, --signal="KILL"    Signal to send to the container

向容器中的主进程发送SIGKILL信号,或者通过选项--signal发送其他信号。

 

load

Usage: docker load [OPTIONS]

Load an image from a tar archive on STDIN

  -i, --input=""     Read from a tar archive file, instead of STDIN

从文件或者标准输入流中加载一个压缩过的仓库,恢复image和标签。

$ sudo docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
$ sudo docker load < busybox.tar
$ sudo docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
busybox             latest              769b9341d937        7 weeks ago         2.489 MB
$ sudo docker load --input fedora.tar
$ sudo docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
busybox             latest              769b9341d937        7 weeks ago         2.489 MB
fedora              rawhide             0d20aec6529d        7 weeks ago         387 MB
fedora              20                  58394af37342        7 weeks ago         385.5 MB
fedora              heisenbug           58394af37342        7 weeks ago         385.5 MB
fedora              latest              58394af37342        7 weeks ago         385.5 MB
 

login

Usage: docker login [OPTIONS] [SERVER]

Register or log in to a Docker registry server, if no server is specified "https://index.docker.io/v1/" is the default.

  -e, --email=""       Email
  -p, --password=""    Password
  -u, --username=""    Username

如果要登录或注册到自己维护的仓库,可以增加服务器名称参数,例如:

$ sudo docker login localhost:8080
 

logout

Usage: docker logout [SERVER]

Log out from a Docker registry, if no server is specified "https://index.docker.io/v1/" is the default.

例如:

$ sudo docker logout localhost:8080

注意:1.2版本中没有此命令

 

logs

Usage: docker logs [OPTIONS] CONTAINER

Fetch the logs of a container

  -f, --follow=false        Follow log output
  -t, --timestamps=false    Show timestamps
  --tail="all"              Output the specified number of lines at the end of logs (defaults to all logs)

docker logs命令在执行的时候,批量获取日志。 
docker logs --follow命令会把新的日志输入继续追加到容器的STDOUT 和STDERR。 
--tail选项设值为负数或非整数时,按照all处理。这种行为以后可能有变化。

docker logs --timestamp命令将为每一个日志记录添加一个RFC3339Nano格式的时间戳, eg. 2014-09-16T06:17:46.000000000Z。为了保证时间戳的纳秒部分对齐,字符串可能在必要的情况下用0填充。

 

port

Usage: docker port CONTAINER [PRIVATE_PORT[/PROTO]]

List port mappings for the CONTAINER, or lookup the public-facing port that is NAT-ed to the PRIVATE_PORT

不指定PRIVATE_PORT时,可以查看所有的端口映射。反之,只查询私有端口映射。

注意:1.2版本中,PRIVATE_PORT必须指定。

$ sudo docker ps test
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                                            NAMES
b650456536c7        busybox:latest      top                 54 minutes ago      Up 54 minutes       0.0.0.0:1234->9876/tcp, 0.0.0.0:4321->7890/tcp   test
$ sudo docker port test
7890/tcp -> 0.0.0.0:4321
9876/tcp -> 0.0.0.0:1234
$ sudo docker port test 7890/tcp
0.0.0.0:4321
$ sudo docker port test 7890/udp
2014/06/24 11:53:36 Error: No public port '7890/udp' published for test
$ sudo docker port test 7890
0.0.0.0:4321
 

pause

Usage: docker pause CONTAINER

Pause all processes within a container

docker pause命令使用cgroups freezer挂起容器中的所有进程。通常,挂起进程时,使用SIGSTOP信号, 这个信号可以被挂起进程检测到.使用cgroups freezer,进程可以在不意识到和捕获到被挂起信号的情况下挂起,然后进程也就可以恢复。

参考[cgroups freezer documentation] 
(https://www.kernel.org/doc/Documentation/cgroups/freezer-subsystem.txt) 获得更多细节。

 

ps

Usage: docker ps [OPTIONS]

List containers

  -a, --all=false       Show all containers. Only running containers are shown by default.
  --before=""           Show only container created before Id or Name, include non-running ones.
  -f, --filter=[]       Provide filter values. Valid filters:
                          exited=<int> - containers with exit code of <int>
                          status=(restarting|running|paused|exited)
  -l, --latest=false    Show only the latest created container, include non-running ones.
  -n=-1                 Show n last created containers, include non-running ones.
  --no-trunc=false      Don't truncate output
  -q, --quiet=false     Only display numeric IDs
  -s, --size=false      Display sizes
  --since=""            Show only containers created since Id or Name, include non-running ones.

运行docker ps命令来显示两个连接的容器。

$ sudo docker ps
CONTAINER ID        IMAGE                        COMMAND                CREATED              STATUS              PORTS               NAMES
4c01db0b339c        ubuntu:12.04                 bash                   17 seconds ago       Up 16 seconds                           webapp
d7886598dbe2        crosbymichael/redis:latest   /redis-server --dir    33 minutes ago       Up 33 minutes       6379/tcp            redis,webapp/db

docker ps命令默认只显示已运行的容器。为了查看所有容器,使用如下命令: 
docker ps -a

 

过滤

过滤标签(-f--filter)的格式为key=value。如果有多个过滤器,为过滤标签多次设值即可(e.g. --filter "foo=bar" --filter "bif=baz")。

现有过滤器: 
* exited (int - the code of exited containers. Only useful with '--all')

 
所有成功退出的容器
$ sudo docker ps -a --filter 'exited=0'
CONTAINER ID        IMAGE             COMMAND                CREATED             STATUS                   PORTS                      NAMES
ea09c3c82f6e        registry:latest   /srv/run.sh            2 weeks ago         Exited (0) 2 weeks ago   127.0.0.1:5000->5000/tcp   desperate_leakey
106ea823fe4e        fedora:latest     /bin/sh -c 'bash -l'   2 weeks ago         Exited (0) 2 weeks ago                              determined_albattani
48ee228c9464        fedora:20         bash                   2 weeks ago         Exited (0) 2 weeks ago                              tender_torvalds

上述命令,可以查出所有exit code为0的容器。

 

pull

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

Pull an image or a repository from the registry

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

大多数image基于Docker Hub中的基础image进行创建。 
Docker Hub 包含了很多预先编译好的image。你可以直接用pull命令将这些image下载到本地,这样你就不需要自己定义并配置image了。

也可以手动指定pullimage时的仓库位置。例如,如果你设置了本地仓库,你可以指定仓库位置为相应路径。

如果要下载某个image或者一组image(即,一个仓库),使用docker pull命令。

$ sudo docker pull debian
# will pull the debian:latest image, its intermediate layers
# and any aliases of the same id
$ sudo docker pull debian:testing
# will pull the image named ubuntu:trusty, ubuntu:14.04
# which is an alias of the same image
# and any intermediate layers it is based on.
# (Typically the empty `scratch` image, a MAINTAINER layer,
# and the un-tarred base).
$ sudo docker pull --all-tags centos
# will pull all the images from the centos repository
$ sudo docker pull registry.hub.docker.com/debian
# manually specifies the path to the default Docker registry. This could
# be replaced with the path to a local registry to pull from another source.
 

push

Usage: docker push NAME[:TAG]

Push an image or a repository to the registry

使用docker push命令在Docker Hub 
上分享image。

 

restart

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

Restart a running container

  -t, --time=10      Number of seconds to try to stop for before killing the container. Once killed it will then be restarted. Default is 10 seconds.

重启一个容器。

 

rm

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

Remove one or more containers

  -f, --force=false      Force the removal of a running container (uses SIGKILL)
  -l, --link=false       Remove the specified link and not the underlying container
  -v, --volumes=false    Remove the volumes associated with the container

销毁容器。默认只能销毁已关闭的容器。使用-f选项强制删除。

 

示例

$ sudo docker rm /redis
/redis

此命令销毁名为/redis的容器.

$ sudo docker rm --link /webapp/redis
/webapp/redis

此命令会销毁容器 /webapp/redis之间的网络关联,而不销毁容器。

$ sudo docker rm --force redis
redis

已运行的容器/redis中的主线程将会收到SIGKILL信号,关闭容器,然后容器会被销毁。

使用命令docker rm $(docker ps -a -q)销毁所有已停止的容器。命令docker ps 
-a -q
可以查询出所有容器的ID,并传递给docker rm命令,任何运行中的容器不会被销毁。

 

rmi

Usage: docker rmi [OPTIONS] IMAGE [IMAGE...]

Remove one or more images

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

删除image。

 

删除带标签的image

可以使用短格式或长格式的image ID来删除image,也可以使用image名称来删除。如果image有多个名称,必须使用rmi命令逐个删除这些名字,然后才能删除image。

$ sudo docker images
REPOSITORY                TAG                 IMAGE ID            CREATED             SIZE
test1                     latest              fd484f19954f        23 seconds ago      7 B (virtual 4.964 MB)
test                      latest              fd484f19954f        23 seconds ago      7 B (virtual 4.964 MB)
test2                     latest              fd484f19954f        23 seconds ago      7 B (virtual 4.964 MB)

$ sudo docker rmi fd484f19954f
Error: Conflict, cannot delete image fd484f19954f because it is tagged in multiple repositories
2013/12/11 05:47:16 Error: failed to remove one or more images

$ sudo docker rmi test1
Untagged: fd484f19954f4920da7ff372b5067f5b7ddb2fd3830cecd17b96ea9e286ba5b8
$ sudo docker rmi test2
Untagged: fd484f19954f4920da7ff372b5067f5b7ddb2fd3830cecd17b96ea9e286ba5b8

$ sudo docker images
REPOSITORY                TAG                 IMAGE ID            CREATED             SIZE
test                      latest              fd484f19954f        23 seconds ago      7 B (virtual 4.964 MB)
$ sudo docker rmi test
Untagged: fd484f19954f4920da7ff372b5067f5b7ddb2fd3830cecd17b96ea9e286ba5b8
Deleted: fd484f19954f4920da7ff372b5067f5b7ddb2fd3830cecd17b96ea9e286ba5b8
 

run

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

Run a command in a new container

  -a, --attach=[]            Attach to STDIN, STDOUT or STDERR.
  --add-host=[]              Add a custom host-to-IP mapping (host:ip)
  -c, --cpu-shares=0         CPU shares (relative weight)
  --cap-add=[]               Add Linux capabilities
  --cap-drop=[]              Drop Linux capabilities
  --cidfile=""               Write the container ID to the file
  --cpuset=""                CPUs in which to allow execution (0-3, 0,1)
  -d, --detach=false         Detached mode: run the container in the background and print the new container ID
  --device=[]                Add a host device to the container (e.g. --device=/dev/sdc:/dev/xvdc)
  --dns=[]                   Set custom DNS servers
  --dns-search=[]            Set custom DNS search domains
  -e, --env=[]               Set environment variables
  --entrypoint=""            Overwrite the default ENTRYPOINT of the image
  --env-file=[]              Read in a line delimited file of environment variables
  --expose=[]                Expose a port from the container without publishing it to your host
  -h, --hostname=""          Container host name
  -i, --interactive=false    Keep STDIN open even if not attached
  --link=[]                  Add link to another container in the form of name:alias
  --lxc-conf=[]              (lxc exec-driver only) Add custom lxc options --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1"
  -m, --memory=""            Memory limit (format: <number><optional unit>, where unit = b, k, m or g)
  --name=""                  Assign a name to the container
  --net="bridge"             Set the Network mode for the container
                               'bridge': creates a new network stack for the container on the docker bridge
                               'none': no networking for this container
                               'container:<name|id>': reuses another container network stack
                               'host': use the host network stack inside the container.  Note: the host mode gives the container full access to local system services such as D-bus and is therefore considered insecure.
  -P, --publish-all=false    Publish all exposed ports to the host interfaces
  -p, --publish=[]           Publish a container's port to the host
                               format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort
                               (use 'docker port' to see the actual mapping)
  --privileged=false         Give extended privileges to this container
  --restart=""               Restart policy to apply when a container exits (no, on-failure[:max-retry], always)
  --rm=false                 Automatically remove the container when it exits (incompatible with -d)
  --sig-proxy=true           Proxy received signals to the process (even in non-TTY mode). SIGCHLD, SIGSTOP, and SIGKILL are not proxied.
  -t, --tty=false            Allocate a pseudo-TTY
  -u, --user=""              Username or UID
  -v, --volume=[]            Bind mount a volume (e.g., from the host: -v /host:/container, from Docker: -v /container)
  --volumes-from=[]          Mount volumes from the specified container(s)
  -w, --workdir=""           Working directory inside the container

docker run命令首先在指定的image上创建出一个可读写的容器层,然后使用指定命令来启动这个容器。 也就是说,docker run等价于/containers/create,然后/containers/(id)/start这两个操作的作何。已关闭的容器,可以使用docker start重启,并且恢复所有关闭之前的改动。使用docker ps -a来查看所有容iq。

docker run命令可以与docker commit命令联合使用,来改变容器运行的命令。参考Docker User Guide 获得更多 --expose-p-P--link等命令行参数的细节

 

示例

$ sudo docker run --cidfile /tmp/docker_test.cid ubuntu echo "test"

此命令将会创建一个容器,并在控制台输出test字符串。cidfile选项使docker创建一个新的文件,并将容器的ID写入到相应文件中。如果这个文件已经存在了,doker命令行将会报错。当docker run的容器退出之后,这个文件的文件流将会被关闭。

$ sudo docker run -t -i --rm ubuntu bash
root@bc338942ef20:/# mount -t tmpfs none /mnt
mount: permission denied

上述命令不会工作,因为默认情况下,容器中的大多数潜在危险度较高的命令都是不允许执行的,包括cap_sys_admin(要求挂载文件系统)。但是,使用--privileged选项创建的容器是可以运行这些命令的。

$ sudo docker run --privileged ubuntu bash
root@50e3f57e16e6:/# mount -t tmpfs none /mnt
root@50e3f57e16e6:/# df -h
Filesystem      Size  Used Avail Use% Mounted on
none            1.9G     0  1.9G   0% /mnt

--privileged选项会启动容器的所有能力,并且通过device控制组(cgroup)来提高容器的上限能力。也就是说,这种情况下的容器几乎可以做所有主机可以做的事。使用该选项的主要目的是为了满足某些特殊情况,比如说:在docker容器中运行docker容器。

$ sudo docker  run -w /path/to/dir/ -i -t  ubuntu pwd

-w选项使命令在指定目录中执行,在上述例子中为/path/to/dir/.如果指定路径不存在,这个目录将会在容器中被创建出来。

$ sudo docker  run  -v `pwd`:`pwd` -w `pwd` -i -t  ubuntu pwd

-v选项将主机上的当前目录挂载到容器中的相应目录。-w选项使用pwd的返回值来切换目录,并使命令在相应目录中执行。上面这个组合使用容器中的命令,对当前主机上的相应工作目录进行执行。

$ sudo docker run -v /doesnt/exist:/foo -w /foo -i -t ubuntu bash

如果主机上的相应的绑定挂载卷目录不存在,docker会自动在主机上创建相应目录。上述例子中,docker会在启动容器之前,在主机上创建/doesnt/exist文件夹。

$ sudo docker run -t -i -v /var/run/docker.sock:/var/run/docker.sock -v ./static-docker:/usr/bin/docker busybox sh

通过静态地对docker unix套接字和docker二进制文件进行绑定挂载(就像[https://get.docker.com]
https://get.docker.com)中那样),可以使容器创建和操作主机上的docker守护程序。

$ sudo docker run -p 127.0.0.1:80:8080 ubuntu bash

上述命令,将主机127.0.0.1上的80端口绑定到容器中的8080端口。Docker User Guide中详细介绍了如果控制docker中的端口。

$ sudo docker run --expose 80 ubuntu bash

上述命令将容器中的80端口在通信链路中暴露出来,但不把它和主机的网卡绑定起来。Docker User Guide中详细介绍了如果控制docker中的端口。 
$ sudo docker run -e MYVAR1 --env MYVAR2=foo --env-file ./env.list ubuntu bash

上述命令设置了容器中的环境变量。有三个选项可以达到这个目的。-e--env这两个选项通过环境变量名和值的方式设置环境变量值,如果没有传递“=”号,则将环境变量名作为值使用。--env-file通过指定文件的方式,将文件中的所有环境变量设置到容器中。-e--env--env-file都可以多次设值。无论参数设置的顺序是什么,docker***总是*先处理--env-file选项指定的文件,然后再按顺序处理-e--env选项的值. 通过这种方式,可以使用-e--env来覆盖指定环境变量的值。

$ cat ./env.list
TEST_FOO=BAR
$ sudo docker run --env TEST_FOO="This is a test" --env-file ./env.list busybox env | grep TEST_FOO
TEST_FOO=This is a test

--env-file选项接收文件名,约定文件中的每一行都是VAR=VAL格式,仿照--env的值得格式. 注释必须以#开头。

--env-file指定的文件格式示例如下:

$ cat ./env.list
TEST_FOO=BAR

# this is a comment
TEST_APP_DEST_HOST=10.10.0.127
TEST_APP_DEST_PORT=8888

# pass through this variable from the caller
TEST_PASSTHROUGH
$ sudo TEST_PASSTHROUGH=howdy docker run --env-file ./env.list busybox env
HOME=/
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=5198e0745561
TEST_FOO=BAR
TEST_APP_DEST_HOST=10.10.0.127
TEST_APP_DEST_PORT=8888
TEST_PASSTHROUGH=howdy

$ sudo docker run --name console -t -i ubuntu bash

上述容器会创建一个名为console的容器,并且可以通过交互bash来操作容器。

$ sudo docker run --link /redis:redis --name console ubuntu bash

--link选项将名为/redis的容器,通过假名redis连接到新的容器中.新的容器可以通过环境变量访问redis容器中的网络和环境。 
--name选项将名称console设置给新创建的容器。

$ sudo docker run --volumes-from 777f7dc92da7 --volumes-from ba8c0c54f0f2:ro -i -t ubuntu pwd

--volumes-from选项将指定的容器中的所有卷挂载到创建出的容器上,可以使用这个选项来多次指定值。容器ID值后面可以使用:ro:rw作为后缀,使容器的卷以只读或读写模式挂载到新容器上。默认情况下,卷挂载的模式(读写或只读)与此卷在指定容器上的原有挂载模式相同。

-a选项使docker run命令去绑定容器的STDINSTDOUTSTDERR,使你在虚拟机的时候可以更容易地操作容器的输入和输出。

$ echo "test" | sudo docker run -i -a stdin ubuntu cat -

上述命令,将数据"test"通过管道和-a选项设置为容器的STDIN的标准输入,并将创建出的容器ID输出到控制台。

$ sudo docker run -a stderr ubuntu echo test

上述命令中,我们只把容器的STDERR绑定了,因此只有在有错误时,上述命令才会打印出信息。容器的日志仍然存储在STDERRSTDOUT中。

$ cat somefile | sudo docker run -i -a stdin mybuilder dobuild

上述命令中,演示了如何将一个文件的内容作为容器命令dobuild的输入。dobuild命令完成后,将输出容器ID,并且dobuild过程中产生的日志可以使用docker logs查看。这个例子可以用于将文件或其他内容输入容器,并在容器运行结束后获得容器ID。

$ sudo docker run --device=/dev/sdc:/dev/xvdc --device=/dev/sdd --device=/dev/zero:/dev/nulo -i -t ubuntu ls -l /dev/{xvdc,sdd,nulo} 
brw-rw---- 1 root disk 8, 2 Feb 9 16:05 /dev/xvdc 
brw-rw---- 1 root disk 8, 3 Feb 9 16:05 /dev/sdd 
crw-rw-rw- 1 root root 1, 5 Feb 9 16:05 /dev/nulo 
很多情况下,你会需要直接把主机上的设备暴露给容器使用,--device选项可以完成这个功能。例如,未授权的容器(不使用--privileged选项创建的容器)可以通过--device选项使容器中的应用直接访问指定块设备、音频设备或loop device。

注意

--device选项无法安全地用于临时设备(ephemeral devices)。 
任何有可能被移除的块设备都不应该通过--device选项添加给未受信任的容器。

完整示例:

$ sudo docker run -d --name static static-web-files sh
$ sudo docker run -d --expose=8098 --name riak riakserver
$ sudo docker run -d -m 100m -e DEVELOPMENT=1 -e BRANCH=example-code -v $(pwd):/app/bin:ro --name app appserver
$ sudo docker run -d -p 1443:443 --dns=10.0.0.1 --dns-search=dev.org -v /var/log/httpd --volumes-from static --link riak --link app -h www.sven.dev.org --name web webserver
$ sudo docker run -t -i --rm --volumes-from web -w /var/log/httpd busybox tail -f access.log

上述命令展示了五个可能用于测试web应用变更的容器的创建时的使用参数。 
1. 通过image static-web-files在后台创建一个名为static的容器。在这个容器中,包含了CSS、图片和静态HTML文件等静态内容(static-web-files这个image在构建过程中,在Dockerfile中通过VOLUME来是web服务器可以使用这些内容)。 
2. 通过image riakserver创建一个名为riak的容器,并把端口8098暴露给任何连接到(link)riak容器的其他容器。 
3. 使用image appserver创建名为app的容器,并限制容器的最大内存使用量为100MB,并设置了两个环境变量——DEVELOPMENTBRANCH的值,通过-v选项将当前目录$(pwd)以只读模式挂载到容器中的/app/bin目录。 
4.使用image webserver创建名为web的容器。通过-p选项将容器中的443端口绑定到docker主机上的1443端口。通过--dns选项设置容器的DNS服务器为10.0.0.1。通过--dns-search设置容器上的DNS查询域(DNS search domain)为dev.org。通过-v选项,使容器在运行时创建卷/var/log/httpd(这个卷可以被其他容器访问)。通过--volumes-from选项导入容器static中暴露的卷。通过--link选项,使新的容器连接到riakapp这两个容器中的已暴露端口。通过-h选项设置容器的主机名为www.sven.dev.org,使这个主机名与预先生成的SSL证书中的主机名保持一致。 
5. 最后,使用image busybox来创建输出日志的容器。--volumes-from选项执行创建的容器使用容器web的卷,并通过-w选项容器中的命令tail -f access.log的工作目录为/var/log/httpd--rm选项表示在容器退出时,docker会自动删除容器。

 

重启策略

在执行docker run命令时,使用--restart选项,可以指定创建爱你出的容器在退出的时候是否需要重启。这个选项的有效值如下所示:

no -容器退出时,不重启容器。

on-failure -容器退出是的状态code非0时,才进行重启。

always - 容器退出时,总是重启容器。 
当使用on-failure策略使,可以使用设置重启重启的最大重试次数,默认情况下,docker会一直尝试重启容器,直到成功为止。

$ sudo docker run --restart=always redis

上述命令中,使用redis 镜像去创建出的容器在退出时总是(always)会自动重启。

$ sudo docker run --restart=on-failure:10 redis

上述命令中,使用redis镜像创建出的容器,会在容器退出失败时(on-failure)时最多重试10次去重启容器。只有在on-failure策略中,这个最大重试次数才会生效。

 

save

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

Save an image(s) to a tar archive (streamed to STDOUT by default)

  -o, --output=""    Write to a file, instead of STDOUT

在标准输出中,使用指定image生成一个压缩后的仓库,在这个仓库中包括所有的父层(parent layer),所有的标签和版本信息。如果指定了repo:tag的值,生成的仓库内容按照相应仓库名和标签进行设置。 
此命令用于创建备份,并且可以用docker load恢复备份。

$ sudo docker save busybox > busybox.tar
$ ls -sh busybox.tar
2.7M busybox.tar
$ sudo docker save --output busybox.tar busybox
$ ls -sh busybox.tar
2.7M busybox.tar
$ sudo docker save -o fedora-all.tar fedora
$ sudo docker save -o fedora-latest.tar fedora:latest

此命令也可以用于对image仓库中的标签进行筛选,如下所示:

$ sudo docker save -o ubuntu.tar ubuntu:lucid ubuntu:saucy

 

search

Search Docker Hub for images

Usage: docker search [OPTIONS] TERM

Search the Docker Hub for images

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

参考[在Docker Hun上搜索共享image]( 
/userguide/dockerrepos/#find-public-images-on-docker-hub),获取使用命令行来查找公网上的共享image的更多细节。

 

start

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

Restart a stopped container

  -a, --attach=false         Attach container's `STDOUT` and `STDERR` and forward all signals to the process
  -i, --interactive=false    Attach container's `STDIN`

启动一个已关闭的容器,当对一个已经启动的容器执行此命令时,不执行任何操作,并且无条件地返回成功。

 

stop

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

Stop a running container by sending `SIGTERM` and then `SIGKILL` after a grace period

  -t, --time=10      Number of seconds to wait for the container to stop before killing it. Default is 10 seconds.

执行此命令时,相应容器中的主线程会收到一个SIGTERM信号,然后一段宽限期后,收到SIGKILL信号。

 

tag

Usage: docker tag [OPTIONS] IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG]

Tag an image into a repository

  -f, --force=false    Force

你可以使用名称和标签对你的image进行分组,然后将image上传到公网上的共享仓库中,参考[通过仓库共享image]( 
/userguide/dockerrepos/#working-with-the-repository)

 

top

Usage: docker top CONTAINER [ps OPTIONS]

Display the running processes of a container

输出容器中调度运行进程信息。

 

unpause

Usage: docker unpause CONTAINER

Unpause all processes within a container

docker unpause命令使用cgroups freezer取消容器中的所有进程的挂起状态。 对应docker pause命令使用。 
参考[cgroups freezer documentation] 
(https://www.kernel.org/doc/Documentation/cgroups/freezer-subsystem.txt) 获得更多细节。

 

version

Usage: docker version

Show the Docker version information.

显示docker客户端和守护进程中的docker版本、API版本、Git提交的版本以及Go语言的版本。

 

wait

Usage: docker wait CONTAINER [CONTAINER...]

Block until a container stops, then print its exit code.

阻塞当前进程,直到指定容器停止,然后打印出容器停止时的exit code。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics