Docker 常用命令总结

举报
jackwangcumt 发表于 2021/11/25 20:58:02 2021/11/25
【摘要】 本文将重点介绍Docker的基础命令、镜像命令和容器命令,也指明了如何拉取镜像,启动容器和进行镜像和容器的文件导出。

1 Docker 概述


      根据百度百科的定义,Docker 是一个开源的跨平台(Linux操作系统、Windows操作系统等)的应用容器引擎,让开发者可以以统一的方式打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何安装了Docker引擎的服务器上,即是一种非常轻量级的虚拟化实现技术。Docker 容器使用沙箱机制,相互之间不会有影响。另外,Docker 相对于其他的虚拟机技术,非常的轻量级,因此资源占用少,启动非常快,可以在几秒进行启动。最后,Docker 不依赖于任何语言、框架。可以很容易地在单台物理机上运行几十个或者上百个Docker容器。正是由于这些特点,Docker被广泛应用于IT领域。

      Docker中有镜像image和容器container的概念,其中类比于面向对象编程当中的类和实例。镜像是静态的,可以导入或者导出文件。容器可以由镜像启动,并可以对外提供服务。另外,容器可以保存为镜像。

2 Docker 基础命令


      这里我们已经安装完成了Ubuntu 18.04的宿主机并可以联网。首先确保当前的Ubuntu 18.04的宿主机安装了Docker环境,如果没有,可以在线安装,命令如下:

su root
apt install docker.io

     在宿主机中查看docker当前的服务状态,可以执行如下命令:

systemctl status docker

    如果是docker正在运行中 ,则输出结果会看到绿色的active标志:

1.jpg

    关于docker服务相关的启动,关闭,重启等命令,如下所示:

#重启
systemctl restart docker
#关闭
systemctl stop docker
#启动
systemctl start docker

      查看docker版本,则可以执行如下命令:

root@jack-pc:/home/jack# docker -v
Docker version 20.10.7, build 20.10.7-0ubuntu5~18.04.3

     执行如下命令,可以查看docker 的详细信息 ,比如docker中容器运行的个数,镜像个数、CPU、内存和安装路径(可以用于切换路径,当默认空间不足的情况下)等信息:

root@jack-pc:/home/jack# docker info
Client:
 Context:    default
 Debug Mode: false

Server:
 Containers: 0
  Running: 0
  Paused: 0
  Stopped: 0
 Images: 0
 Server Version: 20.10.7
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Supports d_type: true
  Native Overlay Diff: true
  userxattr: false
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Cgroup Version: 1
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: runc io.containerd.runc.v2 io.containerd.runtime.v1.linux
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 
 runc version: 
 init version: 
 Security Options:
  apparmor
  seccomp
   Profile: default
 Kernel Version: 5.4.0-90-generic
 Operating System: Ubuntu 18.04.6 LTS
 OSType: linux
 Architecture: x86_64
 CPUs: 1
 Total Memory: 3.844GiB
 Name: jack-pc
 ID: HUTE:QGRS:TFWH:75VF:CTNI:GPEJ:3VRW:TBDY:QPMR:CE6P:7CKV:RRFC
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

WARNING: No swap limit support

  如果需要查看docker支持的命令,可以用如下命令查看:

root@jack-pc:/home/jack# docker --help

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
  image       Manage images
  manifest    Manage Docker image manifests and manifest lists
  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.

To get more help with docker, check out our guides at https://docs.docker.com/go/guides/

对具体的命令,可以执行docker command --help来查看,比如查看commit命令的帮助信息,可以执行如下命令:

root@jack-pc:/home/jack# 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
  -m, --message string   Commit message
  -p, --pause            Pause container during commit (default true)
root@jack-pc:/home/jack# 

如果需要搜索某个镜像,则可以执行如下命令

root@jack-pc:~# docker search mysql
NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql                             MySQL is a widely used, open-source relation…   11728     [OK]       
mariadb                           MariaDB Server is a high performing open sou…   4471      [OK]       
mysql/mysql-server                Optimized MySQL Server Docker images. Create…   872                  [OK]
centos/mysql-57-centos7           MySQL 5.7 SQL database server                   92                   
mysql/mysql-cluster               Experimental MySQL Cluster Docker images. Cr…   89                   
centurylink/mysql                 Image containing mysql. Optimized to be link…   59                

3 Docker 镜像命令


      要使用Docker提供服务,则需要基于镜像来启动容器。首先要解决镜像的问题。镜像是一个基础文件系统,我们可以从网站上下载。有的网站需要用docker login进行登录后才能拉取镜像。拉取镜像命令如下所示:

#最新
root@jack-pc:~# docker pull mysql
#指定版本
root@jack-pc:~# docker pull ubuntu:18.04

     国内拉取镜像可能比较慢,可以修改配置:

root@jack-pc:~# mkdir -p /etc/docker
root@jack-pc:~# vi /etc/docker/daemon.json
###########################################
{
  "registry-mirrors": ["http://hub-mirror.c.163.com"]
}
###########################################

      查看Docker镜像列表,可以执行如下命令:

root@jack-pc:~# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
mysql        latest    b05128b000dd   8 days ago    516MB
ubuntu       18.04     5a214d77f5d7   7 weeks ago   63.1MB

      有了镜像后,就可以用docker run 命令来根据镜像来启动,这个命令有很多参数:

root@jack-pc:~# docker run --help

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

Run a command in a new container

Options:
      --add-host list                  Add a custom host-to-IP mapping (host:ip)
  -a, --attach list                    Attach to STDIN, STDOUT or STDERR
      --blkio-weight uint16            Block IO (relative weight), between 10 and 1000, or 0
                                       to disable (default 0)
      --blkio-weight-device list       Block IO weight (relative device weight) (default [])
      --cap-add list                   Add Linux capabilities
      --cap-drop list                  Drop Linux capabilities
      --cgroup-parent string           Optional parent cgroup for the container
      --cgroupns string                Cgroup namespace to use (host|private)
                                       'host':    Run the container in the Docker host's
                                       cgroup namespace
                                       'private': Run the container in its own private cgroup
                                       namespace
                                       '':        Use the cgroup namespace as configured by
                                       the
                                                  default-cgroupns-mode option on the daemon
                                       (default)
      --cidfile string                 Write the container ID to the file
      --cpu-period int                 Limit CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int                  Limit CPU CFS (Completely Fair Scheduler) quota
      --cpu-rt-period int              Limit CPU real-time period in microseconds
      --cpu-rt-runtime int             Limit CPU real-time runtime in microseconds
  -c, --cpu-shares int                 CPU shares (relative weight)
      --cpus decimal                   Number of CPUs
      --cpuset-cpus string             CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string             MEMs in which to allow execution (0-3, 0,1)
  -d, --detach                         Run container in background and print container ID
      --detach-keys string             Override the key sequence for detaching a container
      --device list                    Add a host device to the container
      --device-cgroup-rule list        Add a rule to the cgroup allowed devices list
      --device-read-bps list           Limit read rate (bytes per second) from a device
                                       (default [])
      --device-read-iops list          Limit read rate (IO per second) from a device (default [])
      --device-write-bps list          Limit write rate (bytes per second) to a device
                                       (default [])
      --device-write-iops list         Limit write rate (IO per second) to a device (default [])
      --disable-content-trust          Skip image verification (default true)
      --dns list                       Set custom DNS servers
      --dns-option list                Set DNS options
      --dns-search list                Set custom DNS search domains
      --domainname string              Container NIS domain name
      --entrypoint string              Overwrite the default ENTRYPOINT of the image
  -e, --env list                       Set environment variables
      --env-file list                  Read in a file of environment variables
      --expose list                    Expose a port or a range of ports
      --gpus gpu-request               GPU devices to add to the container ('all' to pass all
                                       GPUs)
      --group-add list                 Add additional groups to join
      --health-cmd string              Command to run to check health
      --health-interval duration       Time between running the check (ms|s|m|h) (default 0s)
      --health-retries int             Consecutive failures needed to report unhealthy
      --health-start-period duration   Start period for the container to initialize before
                                       starting health-retries countdown (ms|s|m|h) (default 0s)
      --health-timeout duration        Maximum time to allow one check to run (ms|s|m|h)
                                       (default 0s)
      --help                           Print usage
  -h, --hostname string                Container host name
      --init                           Run an init inside the container that forwards signals
                                       and reaps processes
  -i, --interactive                    Keep STDIN open even if not attached
      --ip string                      IPv4 address (e.g., 172.30.100.104)
      --ip6 string                     IPv6 address (e.g., 2001:db8::33)
      --ipc string                     IPC mode to use
      --isolation string               Container isolation technology
      --kernel-memory bytes            Kernel memory limit
  -l, --label list                     Set meta data on a container
      --label-file list                Read in a line delimited file of labels
      --link list                      Add link to another container
      --link-local-ip list             Container IPv4/IPv6 link-local addresses
      --log-driver string              Logging driver for the container
      --log-opt list                   Log driver options
      --mac-address string             Container MAC address (e.g., 92:d0:c6:0a:29:33)
  -m, --memory bytes                   Memory limit
      --memory-reservation bytes       Memory soft limit
      --memory-swap bytes              Swap limit equal to memory plus swap: '-1' to enable
                                       unlimited swap
      --memory-swappiness int          Tune container memory swappiness (0 to 100) (default -1)
      --mount mount                    Attach a filesystem mount to the container
      --name string                    Assign a name to the container
      --network network                Connect a container to a network
      --network-alias list             Add network-scoped alias for the container
      --no-healthcheck                 Disable any container-specified HEALTHCHECK
      --oom-kill-disable               Disable OOM Killer
      --oom-score-adj int              Tune host's OOM preferences (-1000 to 1000)
      --pid string                     PID namespace to use
      --pids-limit int                 Tune container pids limit (set -1 for unlimited)
      --platform string                Set platform if server is multi-platform capable
      --privileged                     Give extended privileges to this container
  -p, --publish list                   Publish a container's port(s) to the host
  -P, --publish-all                    Publish all exposed ports to random ports
      --pull string                    Pull image before running ("always"|"missing"|"never")
                                       (default "missing")
      --read-only                      Mount the container's root filesystem as read only
      --restart string                 Restart policy to apply when a container exits
                                       (default "no")
      --rm                             Automatically remove the container when it exits
      --runtime string                 Runtime to use for this container
      --security-opt list              Security Options
      --shm-size bytes                 Size of /dev/shm
      --sig-proxy                      Proxy received signals to the process (default true)
      --stop-signal string             Signal to stop a container (default "SIGTERM")
      --stop-timeout int               Timeout (in seconds) to stop a container
      --storage-opt list               Storage driver options for the container
      --sysctl map                     Sysctl options (default map[])
      --tmpfs list                     Mount a tmpfs directory
  -t, --tty                            Allocate a pseudo-TTY
      --ulimit ulimit                  Ulimit options (default [])
  -u, --user string                    Username or UID (format: <name|uid>[:<group|gid>])
      --userns string                  User namespace to use
      --uts string                     UTS namespace to use
  -v, --volume list                    Bind mount a volume
      --volume-driver string           Optional volume driver for the container
      --volumes-from list              Mount volumes from the specified container(s)
  -w, --workdir string                 Working directory inside the container

核心参数解释如下:

-a stdin: 指定标准输入输出内容类型,可选 STDIN/STDOUT/STDERR 三项;

-d: 后台运行容器,并返回容器ID;

-i: 以交互模式运行容器,通常与 -t 同时使用;

-p: 指定端口映射,格式为:主机(宿主)端口:容器端口

-t: 为容器重新分配一个伪输入终端,通常与 -i 同时使用;

--name="nginx": 为容器指定一个名称;

-v: 绑定一个数据目录,可以实现宿主机目录和容器的目录之间的映射。

-h "mars": 指定容器的hostname;

-e username="jack": 设置环境变量;

--cpuset="0-2" or --cpuset="0,1,2": 绑定容器到指定CPU运行;

-m :设置容器使用内存最大值;

--dns 8.8.8.8: 指定容器使用的DNS服务器,默认和宿主一致;

--dns-search example.com: 指定容器DNS搜索域名,默认和宿主一致;

启动一个最简单的容器命令如下所示:

root@jack-pc:~# docker run -it ubuntu:18.04  bash
root@e8b2b20c2796:/# 

其中的 e8b2b20c2796 为容器ID。如果想让镜像导出文件,则执行如下命令:

root@jack-pc:~# docker save 5a214d77f5d7 -o ubuntu-18.04.tar
root@jack-pc:~# ls
AscendProjects  snap  tmp  ubuntu-18.04.tar
root@jack-pc:~# 

删除镜像(当前镜像没有被任何容器使用才可以删除,也可以强制删除)可以用如下命令:

root@jack-pc:~# docker rmi 5a214d77f5d7
Error response from daemon: conflict: unable to delete 5a214d77f5d7 (must be forced) 
- image is being used by stopped container 6233d0b078e2
root@jack-pc:~# docker rmi -f 5a214d77f5d7
Untagged: ubuntu:18.04
Untagged: ubuntu@sha256:0fedbd5bd9fb72089c7bbca476949e10593cebed9b1fb9edf5b79dbbacddd7d6
Deleted: sha256:5a214d77f5d747e6ed81632310baa6190301feeb875cf6bf9da560108fa09972

从文件加载镜像,并指定tag,可以用如下命令:

root@jack-pc:~# docker images
REPOSITORY   TAG       IMAGE ID       CREATED      SIZE
mysql        latest    b05128b000dd   8 days ago   516MB
root@jack-pc:~# docker load -i ubuntu-18.04.tar
Loaded image ID: sha256:5a214d77f5d747e6ed81632310baa6190301feeb875cf6bf9da560108fa09972
root@jack-pc:~# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
mysql        latest    b05128b000dd   8 days ago    516MB
<none>       <none>    5a214d77f5d7   7 weeks ago   63.1MB
root@jack-pc:~# docker tag 5a214d77f5d7 ubuntu:18.04
root@jack-pc:~# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
mysql        latest    b05128b000dd   8 days ago    516MB
ubuntu       18.04     5a214d77f5d7   7 weeks ago   63.1MB

3 Docker 容器命令


      可以用如下命令查看容器列表:

root@jack-pc:~# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
root@jack-pc:~# docker ps -a
CONTAINER ID   IMAGE          COMMAND      CREATED         STATUS                     PORTS     NAMES
e8b2b20c2796   ubuntu:18.04   "bash"       8 minutes ago   Exited (0) 6 minutes ago             practical_matsumoto
6233d0b078e2   ubuntu:18.04   "-it bash"   9 minutes ago   Created                              mystifying_elgamal

      其中的docker ps可以查看当前运行的容器,而docker ps -a 可以查看所有的容器,包括停止的容器信息。从上可知,即使容器删除了,但是基于镜像创建的容器还在。我们启动容器用如下命令:

root@jack-pc:~# docker start e8b2b20c2796
e8b2b20c2796
root@jack-pc:~# docker attach e8b2b20c2796
root@e8b2b20c2796:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@e8b2b20c2796:/# cd /root
root@e8b2b20c2796:~# ls
root@e8b2b20c2796:~# mkdir mysoft
root@e8b2b20c2796:~# ls
mysoft
root@e8b2b20c2796:~# exit
exit
root@jack-pc:~# 

      删除容器用如下命令:

root@jack-pc:~# docker rm 6233d0b078e2
6233d0b078e2
root@jack-pc:~# docker ps -a
CONTAINER ID   IMAGE          COMMAND   CREATED          STATUS                      PORTS     NAMES
e8b2b20c2796   ubuntu:18.04   "bash"    12 minutes ago   Exited (0) 59 seconds ago             practical_matsumoto

     重启容器用如下命令:

root@jack-pc:~# docker restart e8b2b20c2796
e8b2b20c2796
root@jack-pc:~# docker attach e8b2b20c2796
root@e8b2b20c2796:/# cd /root
root@e8b2b20c2796:~# ls
mysoft
root@e8b2b20c2796:~# 

     容器保存为镜像,可以执行如下命令:

root@jack-pc:~# docker commit -a "jack" -m "ubuntu v2" e8b2b20c2796 myubuntu:v2.0 
sha256:b4162cc2b11260985ac5f3c377ad4fc698012ec6867331b7f5f6a6f5ca64f884
root@jack-pc:~# docker images
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
myubuntu     v2.0      b4162cc2b112   7 seconds ago   63.1MB
mysql        latest    b05128b000dd   8 days ago      516MB
ubuntu       18.04     5a214d77f5d7   7 weeks ago     63.1MB

    将容器导出为文件,执行如下命令:

docker export -o ubuntu-`date +%Y%m%d`.tar e8b2b20c2796

    结果如下所示:

root@jack-pc:~# docker export -o ubuntu-`date +%Y%m%d`.tar e8b2b20c2796
root@jack-pc:~# ls
AscendProjects  snap  tmp  ubuntu-18.04.tar  ubuntu-20211125.tar

    修改容器的名称,执行如下命令:

root@jack-pc:~# docker ps -a
CONTAINER ID   IMAGE          COMMAND   CREATED          STATUS                     PORTS     NAMES
e8b2b20c2796   ubuntu:18.04   "bash"    21 minutes ago   Exited (0) 4 minutes ago             practical_matsumoto
root@jack-pc:~# docker rename e8b2b20c2796 myubuntu
root@jack-pc:~# docker ps -a
CONTAINER ID   IMAGE          COMMAND   CREATED          STATUS                     PORTS     NAMES
e8b2b20c2796   ubuntu:18.04   "bash"    22 minutes ago   Exited (0) 5 minutes ago             myubuntu

     容器自动启动,可以执行如下配置:

root@jack-pc:~# docker  update --restart=always e8b2b20c2796
e8b2b20c2796

    reboot重启宿主机后,可以通过如下命令查看:

jack@jack-pc:~$ su root
Password: 
root@jack-pc:/home/jack# docker ps
CONTAINER ID   IMAGE          COMMAND   CREATED          STATUS          PORTS     NAMES
e8b2b20c2796   ubuntu:18.04   "bash"    25 minutes ago   Up 49 seconds             myubuntu
root@jack-pc:/home/jack# 

     由此可知,自动启动配置成功。当前容器还可以通过docker cp 来进行文件的拷贝(不启动容器也可以根据路径进行拷贝)。

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。