Docker容器技术-命令进阶

时间:2021-11-26 10:01:26

一、基本命令

1.Docker布尔型选项

使用某选项但没有提供参数,等同于把选项设置为true,要改变它的值,唯一的方法是将其设置成false。

找出一个选项的默认值是true还是false:

[root@bogon ~]# docker --help

Usage:	docker COMMAND

A self-sufficient runtime for containers

Options:
--config string Location of client config files (default "/root/.docker")
-D, --debug Enable debug mode
--help Print usage
-H, --host list Daemon socket(s) to connect to
-l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
--tls Use TLS; implied by --tlsverify
--tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem")
--tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem")
--tlskey string Path to TLS key file (default "/root/.docker/key.pem")
--tlsverify Use TLS and verify the remote
-v, --version Print version information and quit

设置默认值:

[root@bogon ~]# docker run --sig-proxy=false
[root@bogon ~]# docker run --read-only=true

2.run命令

控制容器的生命周期以及基本运行模式

-a, --attach list                    Attach to STDIN, STDOUT or STDERR
把指定的数据流(ETDOUT)连接至终端;若未指定,则默认连接stdout和stderr;若数据流未指定,容器以交互模式(-i)启动,则stdin被连接至终端。 -d, --detach Run container in background and print container ID
使容器在“分离”模式下运行;容器会在后台运行,而命令的返回值是容器的ID。 -i, --interactive Keep STDIN open even if not attached
保持stdin打开。一般与-t同时使用,用作启动交互式会话的容器。 --restart string Restart policy to apply when a container exits (default "no")
配置Docker在什么情况下尝试重启已退出的容器。
参数no为永远不会尝试重启容器;
参数always指不管退出状态是什么,总会尝试重启;
参数on-failure仅当退出状态不为0时重启,并可以追加一个可选参数,指定尝试次数,超过次数会放弃(未指定会一直重试);
例如:
[root@bogon ~]# docker run --restart on-failure:10 postgres --rm Automatically remove the container when it exits
退出时自动删除容器,不能与-d同时使用。 -t, --tty Allocate a pseudo-TTY
分配一个伪终端,通常与-t使用,启动交互式容器。

允许设置容器名称和变量

-e, --env list                       Set environment variables
设置容器内的环境变量。
例如:
[root@bogon ~]# docker run -e var1=var -e var2="val 2" debian env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=9eb154072928
var1=var
var2=val 2
HOME=/root --env-file list Read in a file of environment variables
可以经文件传入环境变量。 -h, --hostname string Container host name
设置容器的unix主机名NAME。
例如:
[root@bogon ~]# docker run -h "myhost" debian hostname --name string Assign a name to the container
把string设置为容器的名称。

允许用户进行数据卷的设置

说明:

数据卷—即一个容器中的文件或目录,实际属于主机的文件系统,而非容器的联合文件系统的一部分。

-v, --volume list                    Bind mount a volume
用来设置数据卷。
1)仅指定容器中的目录,docker会自行选定一个主机上的目录与之绑定;
2)指定与容器目录绑定的主机目录; --volumes-from list Mount volumes from the specified container(s)
挂载指定容器拥有的数据卷。

网络连接

--expose list                    Expose a port or a range of ports
指定容器将会使用的端口或端口范围,但不会把端口打开;与-P参数同时使用或在连接容器时才有用。 --link list Add link to another container
建立一个与指定容器连接的内部网络接口。 -p, --publish list Publish a container's port(s) to the host
“发布”容器的端口,使主机能访问它;若未指定端口,会随机分配一个高端口;或指定端口在主机的那个网络接口开放。
使用docker port查看分配了哪个端口及映射关系。 -P, --publish-all Publish all exposed ports to random ports
“发布”所有已指定为开放(exposed)的容器端口,使主机能访问它们;每个容器端口均对应一个随机高端口。

控制容器权限及性能

--entrypoint string              Overwrite the default ENTRYPOINT of the image
把参数string指定为容器的入口,覆盖任何Dockerfile中的ENTRYPOINT指令。 -u, --user string Username or UID (format: <name|uid>[:<group|gid>])
设置命令运行时所使用的用户;可以以用户名或UID指定;同样会覆盖Dockerfile中的USER指令。 -w, --workdir string Working directory inside the container
将参数的路径设置为容器的工作目录;会覆盖Dockerfile中的WORKDIR指令。

3.容器管理

1) docker attach命令

允许用户查看容器内的主进程或与之交互。

[root@bogon ~]# 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
--help Print usage
--no-stdin Do not attach STDIN
--sig-proxy Proxy all received signals to the process (default true)
[root@bogon ~]# ID=$(docker run -d debian sh -c "while true; do echo 'tick'; sleep 2; done;")
[root@bogon ~]# docker attach $ID
tick
tick
tick
tick

2)docker create命令

从镜像创建容器,但不启动。

[root@bogon ~]# docker start --help

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

Start one or more stopped containers

Options:
-a, --attach Attach STDOUT/STDERR and forward signals
--detach-keys string Override the key sequence for detaching a container
--help Print usage
-i, --interactive Attach container's STDIN

3) docker cp命令

在容器和主机之间复制文件和目录

[root@bogon ~]# docker cp --help

Usage:	docker 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)
-L, --follow-link Always follow symbol link in SRC_PATH
--help Print usage

4) docker exec命令

在容器中运行一个命令。用于执行维护工作或替代SSH用作登入容器。

[root@bogon ~]# docker exec --help

Usage:	docker 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
--help Print usage
-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>])
[root@bogon ~]# ID=$(docker run -d debian bash -c \
> "trap 'echo caught' SIGTRAP; while true; do sleep 2; done;")
[root@bogon ~]# docker kill -s SIGTRAP $ID
320175afeec0192844073a00a3ba1fecc6cc15879fcdbbe08683ff63bd0dc215
[root@bogon ~]# docker logs $ID
caught
[root@bogon ~]# docker kill $ID
320175afeec0192844073a00a3ba1fecc6cc15879fcdbbe08683ff63bd0dc215

5) docker pause命令

暂停容器内的所有进程。

进程不会接收到被暂停的信号,因此它们无法执行正常结束或清理的程序。(与docker stop不同)

通过docker unpause命令重启。

[root@bogon ~]# docker pause --help

Usage:	docker pause CONTAINER [CONTAINER...]

Pause all processes within one or more containers

Options:
--help Print usage

6) docker restart命令

重新启动一个或多个容器。

  • 先执行docker stop
  • 再执行docker start
[root@bogon ~]# docker restart --help

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

Restart one or more containers

Options:
--help Print usage
-t, --time int Seconds to wait for stop before killing the container (default 10)

7) docker rm命令

删除一个或多个容器。

默认不会删除任何数据卷。

[root@bogon ~]# docker rm --help

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

Remove one or more containers

Options:
-f, --force Force the removal of a running container (uses SIGKILL)
--help Print usage
-l, --link Remove the specified link
-v, --volumes Remove the volumes associated with the container
[root@bogon ~]# docker rm $(docker ps -aq)
320175afeec0
447963b7b845
9eb154072928
096ff53edbaf
36c220e77949
Error response from daemon: You cannot remove a running container d07dd579ee128a9500b81507764edbcf81aef3281a22eee22fe04c74163c6986. Stop the container before attempting removal or force remove
[root@bogon ~]# docker rm -f $(docker ps -aq)
d07dd579ee12

8) docker start命令

启动一个或多个已停止的容器,或由create创建未启动的容器。

[root@bogon ~]# docker start --help

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

Start one or more stopped containers

Options:
-a, --attach Attach STDOUT/STDERR and forward signals
--detach-keys string Override the key sequence for detaching a container
--help Print usage
-i, --interactive Attach container's STDIN

9) docker stop命令

停止但不删除一个或多个容器。

[root@bogon ~]# docker stop --help

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

Stop one or more running containers

Options:
--help Print usage
-t, --time int Seconds to wait for stop before killing it (default 10)

10) docker unpause命令

重启先前被docker pause命令暂停的容器。

[root@bogon ~]# docker unpause --help

Usage:	docker unpause CONTAINER [CONTAINER...]

Unpause all processes within one or more containers

Options:
--help Print usage

4.Docker信息

[root@bogon ~]# docker info
Containers: 0
Running: 0
Paused: 0
Stopped: 0
Images: 13
Server Version: 17.09.0-ce
Storage Driver: overlay
Backing Filesystem: xfs
Supports d_type: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
Volume: local
...省略部分
[root@bogon ~]# docker version
Client:
Version: 17.09.0-ce
API version: 1.32
Go version: go1.8.3
Git commit: afdb6d4
Built: Tue Sep 26 22:41:23 2017
OS/Arch: linux/amd64 Server:
Version: 17.09.0-ce
API version: 1.32 (minimum version 1.12)
Go version: go1.8.3
Git commit: afdb6d4
Built: Tue Sep 26 22:42:49 2017
OS/Arch: linux/amd64
Experimental: false

5.容器信息

1) docker diff命令

对比容器所使用的镜像,显示容器的文件系统的变化。

[root@bogon ~]# ID=$(docker run -d debian touch /NEW-FILE)
[root@bogon ~]# docker diff $ID
A /NEW-FILE

2) docker events命令

打印守护进程的实时事件。

3) docker inspect命令

把容器或镜像作为参数,获取它们的详细信息(配置、联网、数据卷)。

[root@bogon ~]# docker inspect --help

Usage:	docker inspect [OPTIONS] NAME|ID [NAME|ID...]

Return low-level information on Docker objects

Options:
-f, --format string Format the output using the given Go template
--help Print usage
-s, --size Display total file sizes if the type is container
--type string Return JSON for specified type

4) docker logs命令

输出容器的日志,也就是曾经输出到容器中的STDOUT或STDERR内容。

5) docker port命令

把容器作为参数,列出它的端口映射信息,查看容器内部端口和协议。

[root@bogon ~]# ID=$(docker run -P -d redis)
[root@bogon ~]# docker port $ID
6379/tcp -> 0.0.0.0:32768
[root@bogon ~]# docker port $ID 6379/tcp
0.0.0.0:32768

6) docker ps命令

提供当前容器的高阶信息

[root@bogon ~]# 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
--help Print usage
-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 numeric IDs
-s, --size Display total file sizes

7) docker top命令

把容器作为参数,提供该容器内运行中进程信息。

[root@bogon ~]# ID=$(docker run -d redis)

[root@bogon ~]# docker top $ID
UID PID PPID C STIME TTY TIME CMD
systemd+ 3881 3865 0 00:34 ? 00:00:00 redis-server *:6379 [root@bogon ~]# docker top $ID -axZ
LABEL PID TTY STAT TIME COMMAND
- 3881 ? Ssl 0:00 redis-server *:6379

6.镜像管理

1) docker build命令

从Dockerfile建立镜像

2) docker commit命令

从指定的容器创建镜像。

[root@bogon ~]# 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 <hannibal@a-team.com>")
-c, --change list Apply Dockerfile instruction to the created image
--help Print usage
-m, --message string Commit message
-p, --pause Pause container during commit (default true)
[root@bogon ~]# ID=$(docker run -d redis touch /new-file)
[root@bogon ~]# docker commit -a "Da Yun" -m "Comment" $ID commit:test
sha256:8794a1466b56e19d89b78d62eaa7cc04c5c1cd9fed8cf0a511d57ea387d6065d
[root@bogon ~]# docker images commit
REPOSITORY TAG IMAGE ID CREATED SIZE
commit test 8794a1466b56 10 seconds ago 107MB
[root@bogon ~]# docker run commit:test ls /new-file
/new-file

3) docker export命令

将容器的文件系统中的内容以tar归档的格式导出,并输出到STDOUT。

归档的文件可通过docker import导入,但只会导入文件系统,元数据将丢失。

4) docker history命令

输出镜像中每个镜像层的信息。

5) docker images命令

列出所有本地镜像。

[root@bogon ~]# docker images --help

Usage:	docker images [OPTIONS] [REPOSITORY[:TAG]]

List images

Options:
-a, --all Show all images (default hides intermediate images)
--digests Show digests
-f, --filter filter Filter output based on conditions provided
--format string Pretty-print images using a Go template
--help Print usage
--no-trunc Don't truncate output
-q, --quiet Only show numeric IDs
[root@bogon ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
commit test 8794a1466b56 5 minutes ago 107MB
hubuser/webapp latest cbe52807fcad 8 hours ago 362MB
redis latest 1fb7b6c8c0d0 13 days ago 107MB
debian latest 874e27b628fd 13 days ago 100MB
ubuntu 14.04 dea1945146b9 5 weeks ago 188MB
busybox latest 54511612f1c4 5 weeks ago 1.13MB
[root@bogon ~]# docker images | head -2
REPOSITORY TAG IMAGE ID CREATED SIZE
commit test 8794a1466b56 5 minutes ago 107MB

6) docker import命令

从一个含有文件系统的归档文件创建镜像。

docker export  8794a1466b56 |docker import - flatten:test
docker history flatten:test

7) docker load命令

加载仓库,仓库以tar归档形式从STDIN读入。

仓库可以包含数个镜像和标签,并包含元数据。

8) docker rmi

删除指定的一个或多个镜像。

删除所有被遗留的镜像
docker rmi $(docker images -q -f dangling=true)

9) docker save命令

把指定的镜像或仓库储存到tar归档,并输出到STDOUT。

[root@bogon ~]# docker save -o /tmp/redis.tar redis:latest
[root@bogon ~]# docker rmi redis:latest
Error response from daemon: conflict: unable to remove repository reference "redis:latest" (must force) - container dd923378c826 is using its referenced image 1fb7b6c8c0d0
[root@bogon ~]# docker rmi -f redis:latest
Untagged: redis:latest
Untagged: redis@sha256:07e7b6cb753f8d06a894e22af30f94e04844461ab6cb002c688841873e5e5116
[root@bogon ~]# docker load -i /tmp/redis.tar
Loaded image: redis:latest
[root@bogon ~]# docker images redis
REPOSITORY TAG IMAGE ID CREATED SIZE
redis latest 1fb7b6c8c0d0 13 days ago 107MB

10) docker tag命令

将镜像与一个仓库和标签名称关联。

把ID为1fb7b6c8c0d0的镜像添加到仓库newname
[root@bogon ~]# docker tag 1fb7b6c8c0d0 newname 把newname:latest镜像添加到hdlptz/newname仓库(适用于推送到Hub)
[root@bogon ~]# docker tag newname:latest hdlptz/newname 与上面一样,但标签变为newtag
[root@bogon ~]# docker tag newname:latest hdlptz/newname:newtag 适用于将镜像推送到myregistry.com:5000寄存服务器
[root@bogon ~]# docker tag newname:latest myregistry.com:5000/newname:newtag

7.寄存服务器

1) docker login命令

在指定寄存服务器进行注册或登录。未指定则为Docker Hub。

2) docker logout命令

从Docker寄存服务器注销。

3) docker pull命令

从寄存服务器下载指定镜像。

4) docker push命令

将镜像或仓库推送到寄存服务器。

5) docker search命令

列出Docker Hub上匹配搜索词的公共仓库,结果最多25个仓库。

二、发布容器

将主机8000端口转发至容器80端口
[root@bogon ~]# docker run -d -p 8000:80 nginx
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
bc95e04b23c0: Pull complete
110767c6efff: Pull complete
f081e0c4df75: Pull complete
Digest: sha256:004ac1d5e791e705f12a17c80d7bb1e8f7f01aa7dca7deee6e65a03465392072
Status: Downloaded newer image for nginx:latest
521006b3e1d0b967bbde857f8940274e52418faf79b5bedda6fd36eb9a811e42 [root@bogon ~]# curl localhost:8000
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p> <p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p> <p><em>Thank you for using nginx.</em></p>
</body>
</html>
[root@bogon ~]# ID=$(docker run -d -P nginx)
[root@bogon ~]# docker port $ID 80
0.0.0.0:32769
[root@bogon ~]# curl localhost:32769
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
...省略部分

三、容器互联

link是允许同一主机上的容器互相通信。

[root@bogon ~]# docker run -d --name myredis redis
315436a9429604a1e1eb87dfb3d88358afea9b1a0fae44a67b506fd5015b4d76
[root@bogon ~]# docker run --link myredis:redis debian env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=f53e2bf05ea1
REDIS_PORT=tcp://172.17.0.6:6379
REDIS_PORT_6379_TCP=tcp://172.17.0.6:6379
REDIS_PORT_6379_TCP_ADDR=172.17.0.6
REDIS_PORT_6379_TCP_PORT=6379
REDIS_PORT_6379_TCP_PROTO=tcp
REDIS_NAME=/hopeful_pasteur/redis
REDIS_ENV_GOSU_VERSION=1.10
REDIS_ENV_REDIS_VERSION=4.0.2
REDIS_ENV_REDIS_DOWNLOAD_URL=http://download.redis.io/releases/redis-4.0.2.tar.gz
REDIS_ENV_REDIS_DOWNLOAD_SHA=b1a0915dbc91b979d06df1977fe594c3fa9b189f1f3d38743a2948c9f7634813
HOME=/root

四、利用数据卷和数据容器管理数据

Docker的数据卷是一个目录,并不属于UFS的一部分,它只是在主机上被绑定挂载到容器的一个普通目录。

三种初始化数据卷的方法:

1.通过-v选项宣告一个数据卷

[root@bogon ~]# docker run -it --name container-test -h CONTAINER -v /data debian /bin/bash
root@CONTAINER:/# ls /data
root@CONTAINER:/#

容器中的/data目录便成为一个数据卷;镜像的/data目录中的所有文件将被复制到数据卷中。

查看数据卷在主机上的实际位置:

[root@bogon ~]# docker inspect -f {{.Mounts}} container-test
[{volume 8f85ec52ae72894b6a15065a3fd3f863f94be708cd17969d15516eb6a014d262 /var/lib/docker/volumes/8f85ec52ae72894b6a15065a3fd3f863f94be708cd17969d15516eb6a014d262/_data /data local true }]

2.通过Dockerfile使用VOLUME指令

FROM debian:wheezy
VOLUME /data

注意:

VOLUME指令之后的所有指令不可以对该数据卷有任何修改(这些修改只会在临时容器层内的数据卷上执行,指令结束后将被删除)。

正确做法如下:

FROM debian:wheezy
RUN useradd foo
RUN mkdir /data && touch /data/x
RUN chown -R foo:foo /data
VOLUME /data

3.通过docker run -v用法进行扩展(绑定挂载)

docker run -v /home/adrian/data:/data debian ls /data

氢气可以使用/home/adrian/data目录下的任何文件,如果容器内已有/data目录,它的内容将被数据卷所隐藏。

五、共享数据

  1. -v HOST_DIR:CONTAINER_DIR

2.在运行docker run命令时,传入--volumes-from CONTAINER参数

[root@bogon ~]# docker run -it -h NEWCONTAINER --volumes-from container-test debian /bin/bash
root@NEWCONTAINER:/# ls /data
test-file
root@NEWCONTAINER:/#

3.数据容器

创建数据容器,使之与其他容器分享数据。

docker run --name dbdata postgres echo "Data-only container for postgres"
从postgres镜像创建一个容器,并且初始化镜像中定义的所有数据卷,最后执行echo命令并退出。 docker run -d --volumes-from dbdata --name db1 postgres
使其他容器可以使用这个数据卷 使用相同镜像不会占用任何额外空间,因为你已经下载或创建了用作数据使用方的镜像,这样也让镜像有机会为容器建立任何初始数据,并确保全县设置正确。 删除数据卷满足的条件:
1)容器被docker rm -v命令删除
2)docker run命令执行时带有--rm选项
3)目前没有容器与该数据卷关联
4)该数据卷没有指定使用主机目录