签到成功

知道了

CNDBA社区CNDBA社区

Docker 命令大全

2020-03-29 11:57 2248 1 原创 Docker
作者: dave

在之前的几篇博客我们已经搭建了Docker的测试环境, 了解了docer的部分命令,如下:

Linux 7.7 安装 Docker
https://www.cndba.cn/dave/article/4100
Redhat 7.7 系统上 Docker 安装 MySQL
https://www.cndba.cn/dave/article/4102
Docker 配置国内源
https://www.cndba.cn/dave/article/4101
Docker 搭建私有仓库
https://www.cndba.cn/dave/article/4103

http://www.cndba.cn/cndba/dave/article/4104

本片我们继续研究Docker中的其他命令操作。

1 docker命令清单

Docker 中的所有操作都通过docker命令进行,在安装好的环境中,我们可以直接查看docker命令的帮助。

[root@www.cndba.cn ~]# docker

Usage:  docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/root/.docker")
  -c, --context string     Name of the context to use to connect to the daemon (overrides DOCKER_HOST
                           env var and default context set with "docker context use")
  -D, --debug              Enable debug mode
  -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

Management Commands:
  builder     Manage builds
  config      Manage Docker configs
  container   Manage containers
  context     Manage contexts
  engine      Manage the docker engine
  image       Manage images
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  secret      Manage Docker secrets
  service     Manage services
  stack       Manage Docker stacks
  swarm       Manage Swarm
  system      Manage Docker
  trust       Manage trust on Docker images
  volume      Manage volumes

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  build       Build an image from a Dockerfile
  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
  events      Get real time events from the server
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  history     Show the history of an image
  images      List images
  import      Import the contents from a tarball to create a filesystem image
  info        Display system-wide information
  inspect     Return low-level information on Docker objects
  kill        Kill one or more running containers
  load        Load an image from a tar archive or STDIN
  login       Log in to a Docker registry
  logout      Log out from a Docker registry
  logs        Fetch the logs of a container
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  ps          List containers
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  rmi         Remove one or more images
  run         Run a command in a new container
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  search      Search the Docker Hub for images
  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
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
  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
  version     Show the Docker version information
  wait        Block until one or more containers stop, then print their exit codes

Run 'docker COMMAND --help' for more information on a command.
[root@www.cndba.cn ~]#

帮助的最后一行提到,如果想查看具体命令的帮助,可以使用:docker COMMAND —help。http://www.cndba.cn/cndba/dave/article/4104

[root@www.cndba.cn ~]# 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
  -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
[root@www.cndba.cn ~]#

2 docker命令分类

在上一小节,我们看了docker的帮助,里面的命令太多,这里大致可以分成以下6类。

容器生命周期管理:

run
start/stop/restart
kill
rm
pause/unpause
create
exec

容器操作:

ps
inspect
top
attach
events
logs
wait
export
port

容器rootfs命令

http://www.cndba.cn/cndba/dave/article/4104

commit
cp
diffhttp://www.cndba.cn/cndba/dave/article/4104

镜像仓库

login
pull
push
search

本地镜像管理

images
rmi
tag
build
history
save
load
importhttp://www.cndba.cn/cndba/dave/article/4104

信息和版本查看:

info
version

这些命令都可以通过帮助查看具体的选项:docker COMMAND —help。

http://www.cndba.cn/cndba/dave/article/4104

我们这里看几个常用的命令。

2.1 exec

[root@www.cndba.cn ~]# 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
  -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
[root@www.cndba.cn ~]#


-d :分离模式: 在后台运行
-i :即使没有附加也保持STDIN 打开
-t :分配一个伪终端

这种方法常用来登录容器,当然也可以执行其他操作,比如对数据库的备份。

[root@www.cndba.cn ~]# docker ps -a
CONTAINER ID        IMAGE                        COMMAND                  CREATED             STATUS                      PORTS                    NAMES
4e327b82cd18        192.168.74.203:5000/tomcat   "catalina.sh run"        46 minutes ago      Up 34 minutes               0.0.0.0:8080->8080/tcp   tomcat
34ad82852c64        mysql:latest                 "docker-entrypoint.s…"   11 hours ago        Exited (0) 56 minutes ago                            mysqlserver
[root@www.cndba.cn ~]# docker exec -it 4e327b82cd18 bash
root@4e327b82cd18:/usr/local/tomcat#

2.2 run

docker run :创建一个新的容器并运行一个命令。

[root@www.cndba.cn ~]# 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
      --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)
      --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: <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
[root@www.cndba.cn ~]#


部分选项说明如下:
-a stdin: 指定标准输入输出内容类型,可选 STDIN/STDOUT/STDERR 三项;
-d: 后台运行容器,并返回容器ID;
-i: 以交互模式运行容器,通常与 -t 同时使用;
-P: 随机端口映射,容器内部端口随机映射到主机的高端口
-p: 指定端口映射,格式为:主机(宿主)端口:容器端口
-t: 为容器重新分配一个伪输入终端,通常与 -i 同时使用;
--name="nginx-lb": 为容器指定一个名称;
--dns 8.8.8.8: 指定容器使用的DNS服务器,默认和宿主一致;
--dns-search example.com: 指定容器DNS搜索域名,默认和宿主一致;
-h "mars": 指定容器的hostname;
-e username="ritchie": 设置环境变量;
--env-file=[]: 从指定文件读入环境变量;
--cpuset="0-2" or --cpuset="0,1,2": 绑定容器到指定CPU运行;
-m :设置容器使用内存最大值;
--net="bridge": 指定容器的网络连接类型,支持 bridge/host/none/container: 四种类型;
--link=[]: 添加链接到另一个容器;
--expose=[]: 开放一个端口或一组端口;
--volume , -v: 绑定一个卷

在之前的博客也提到过, docker run 是第一次初始化容器用的,之后容器的管理通过docker start/stop/restart 进行管理。http://www.cndba.cn/cndba/dave/article/4104

2.3 create

与run命令不同,docker create 命令创建一个新的容器但不启动它。 其他选项和run 相同。

http://www.cndba.cn/cndba/dave/article/4104

2.4 ps

docker ps : 列出容器。

[root@www.cndba.cn ~]# 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)
  -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
[root@www.cndba.cn ~]#



选项说明:
OPTIONS说明:
-a :显示所有的容器,包括未运行的。
-f :根据条件过滤显示的内容。
--format :指定返回值的模板文件。
-l :显示最近创建的容器。
-n :列出最近创建的n个容器。
--no-trunc :不截断输出。
-q :静默模式,只显示容器编号。
-s :显示总的文件大小。

[root@www.cndba.cn ~]# docker ps -a
CONTAINER ID        IMAGE                        COMMAND                  CREATED             STATUS                         PORTS                    NAMES
4e327b82cd18        192.168.74.203:5000/tomcat   "catalina.sh run"        53 minutes ago      Up 42 minutes                  0.0.0.0:8080->8080/tcp   tomcat
34ad82852c64        mysql:latest                 "docker-entrypoint.s…"   11 hours ago        Exited (0) About an hour ago                            mysqlserver
[root@www.cndba.cn ~]#

输出详情介绍:
1.CONTAINER ID: 容器 ID。
2.IMAGE: 使用的镜像。
3.COMMAND: 启动容器时运行的命令。
4.CREATED: 容器的创建时间。
5.STATUS: 容器状态。状态有7种:
(1)created(已创建)
(2)restarting(重启中)
(3)running(运行中)
(4)removing(迁移中)
(5)paused(暂停)
(6)exited(停止)
(7)dead(死亡)
6.PORTS: 容器的端口信息和使用的连接类型(tcp/udp)。
7.NAMES: 自动分配的容器名称。

2.5 top

docker top :查看容器中运行的进程信息,支持 ps 命令参数。http://www.cndba.cn/cndba/dave/article/4104

[root@www.cndba.cn ~]# docker ps -a
CONTAINER ID        IMAGE                        COMMAND                  CREATED             STATUS                         PORTS                    NAMES
4e327b82cd18        192.168.74.203:5000/tomcat   "catalina.sh run"        53 minutes ago      Up 42 minutes                  0.0.0.0:8080->8080/tcp   tomcat
34ad82852c64        mysql:latest                 "docker-entrypoint.s…"   11 hours ago        Exited (0) About an hour ago                            mysqlserver

[root@www.cndba.cn ~]# docker top tomcat
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                42288               42271               0                   10:48               pts/0               00:00:12            /usr/local/openjdk-8/bin/java -Djava.util.logging.config.file=/usr/local/tomcat/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -Dorg.apache.catalina.security.SecurityListener.UMASK=0027 -Dignore.endorsed.dirs= -classpath /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar -Dcatalina.base=/usr/local/tomcat -Dcatalina.home=/usr/local/tomcat -Djava.io.tmpdir=/usr/local/tomcat/temp org.apache.catalina.startup.Bootstrap start
[root@www.cndba.cn ~]#

查看所有容器的进程信息:

[root@www.cndba.cn ~]# for i in docker ps |grep Up|awk '{print $1}';do echo / &&docker top $i; done

2.6 logs

docker logs : 获取容器的日志

[root@www.cndba.cn ~]# docker logs --help

Usage:  docker logs [OPTIONS] CONTAINER

Fetch the logs of a container

Options:
      --details        Show extra details provided to logs
  -f, --follow         Follow log output
      --since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42
                       minutes)
      --tail string    Number of lines to show from the end of the logs (default "all")
  -t, --timestamps     Show timestamps
      --until string   Show logs before a timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for
                       42 minutes)
[root@www.cndba.cn ~]#


OPTIONS说明:

-f : 跟踪日志输出
--since :显示某个开始时间的所有日志
-t : 显示时间戳
--tail :仅列出最新N条容器日志

[root@www.cndba.cn ~]# docker logs -f --tail 5 --since="2020-03-29" tomcat
29-Mar-2020 02:50:06.424 INFO [localhost-startStop-3] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/usr/local/tomcat/webapps/examples] has finished in [217] ms
29-Mar-2020 02:50:06.424 INFO [localhost-startStop-3] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/usr/local/tomcat/webapps/host-manager]
29-Mar-2020 02:50:06.442 INFO [localhost-startStop-3] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/usr/local/tomcat/webapps/host-manager] has finished in [18] ms
29-Mar-2020 02:50:06.443 INFO [localhost-startStop-3] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/usr/local/tomcat/webapps/manager]
29-Mar-2020 02:50:06.455 INFO [localhost-startStop-3] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/usr/local/tomcat/webapps/manager] has finished in [12] ms

2.7 cp

docker cp :用于容器与主机之间的数据拷贝。


[root@www.cndba.cn ~]# 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

Use '-' as the source to read a tar archive from stdin
and extract it to a directory destination in a container.
Use '-' as the destination to stream a tar archive of a
container source to stdout.

Options:
  -a, --archive       Archive mode (copy all uid/gid information)
  -L, --follow-link   Always follow symbol link in SRC_PATH
[root@www.cndba.cn ~]#


[root@www.cndba.cn ~]# docker ps -a
CONTAINER ID        IMAGE                        COMMAND                  CREATED             STATUS                         PORTS                    NAMES
4e327b82cd18        192.168.74.203:5000/tomcat   "catalina.sh run"        About an hour ago   Up 54 minutes                  0.0.0.0:8080->8080/tcp   tomcat
34ad82852c64        mysql:latest                 "docker-entrypoint.s…"   12 hours ago        Exited (0) About an hour ago                            mysqlserver
[root@www.cndba.cn ~]#

将容器4e327b82cd18的/usr/local/tomcat/webapps目录拷贝到主机的/tmp目录中。

[root@www.cndba.cn ~]# docker cp  4e327b82cd18:/usr/local/tomcat/webapps /tmp/
[root@www.cndba.cn ~]# ll /tmp/webapps/
total 4
drwxr-xr-x 16 root root 4096 Mar 18 07:13 docs
drwxr-xr-x  6 root root   83 Mar 18 07:13 examples
drwxr-xr-x  5 root root   87 Mar 18 07:13 host-manager
drwxr-xr-x  5 root root  103 Mar 18 07:13 manager
drwxr-xr-x  3 root root  283 Mar 18 07:13 ROOT
[root@www.cndba.cn ~]#

将主机/tmp/webapps目录拷贝到容器4e327b82cd18中,目录重命名为cndba。http://www.cndba.cn/cndba/dave/article/4104

[root@www.cndba.cn ~]# docker cp /tmp/webapps  4e327b82cd18:/cndba
[root@www.cndba.cn ~]# docker exec -it tomcat bash
root@4e327b82cd18:/# ls
bin  boot  cndba  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@4e327b82cd18:/#
root@4e327b82cd18:/usr/local/tomcat# cd /cndba
root@4e327b82cd18:/cndba# ls
ROOT  docs  examples  host-manager  manager
root@4e327b82cd18:/cndba#

将主机/tmp/webapps目录拷贝到容器4e327b82cd18的/cndba目录下。

[root@www.cndba.cn ~]# docker cp /tmp/webapps 4e327b82cd18:/cndba/
[root@www.cndba.cn ~]# docker exec -it tomcat bash
root@4e327b82cd18:/usr/local/tomcat# cd /cndba/
root@4e327b82cd18:/cndba# ls
ROOT  docs  examples  host-manager  manager  webapps
root@4e327b82cd18:/cndba# ls webapps/
ROOT  docs  examples  host-manager  manager
root@4e327b82cd18:/cndba#

版权声明:本文为博主原创文章,未经博主允许不得转载。

用户评论
* 以下用户言论只代表其个人观点,不代表CNDBA社区的观点或立场
dave

dave

关注

人的一生应该是这样度过的:当他回首往事的时候,他不会因为虚度年华而悔恨,也不会因为碌碌无为而羞耻;这样,在临死的时候,他就能够说:“我的整个生命和全部精力,都已经献给世界上最壮丽的事业....."

  • 2296
    原创
  • 3
    翻译
  • 582
    转载
  • 198
    评论
  • 访问:8508372次
  • 积分:4477
  • 等级:核心会员
  • 排名:第1名
精华文章
    最新问题
    查看更多+
    热门文章
      热门用户
      推荐用户
        Copyright © 2016 All Rights Reserved. Powered by CNDBA · 皖ICP备2022006297号-1·

        QQ交流群

        注册联系QQ