Docker系列(二)Docker常用命令

Docker有很多命令,这些命令有助于控制Docker的行为。本文将详细探讨Docker常用命令。

一、Docker镜像常用命令

1、搜索镜像

可使用docker search 命令搜索存放在Docker Hub中的镜像。例如:

docker search java

执行该命令后,Docker就会在Docker Hub中搜索含有java这个关键词的镜像仓库。执行该命令后,可看到类似于如下的表格:

NAME                                         DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
node                                         Node.js is a JavaScript-based platform for s…   5363                [OK]                
tomcat                                       Apache Tomcat is an open source implementati…   1793                [OK]                
java                                         Java is a concurrent, class-based, and objec…   1676                [OK]                
openjdk                                      OpenJDK is an open-source implementation of903                 [OK]                
ghost                                        Ghost is a free and open source blogging pla…   740                 [OK]                
anapsix/alpine-java                          Oracle Java 8 (and 7) with GLIBC 2.23 over A…   296                                     [OK]

该表格包含五列,含义如下。

  • NAME:镜像仓库名称。
  • DESCRIPTION:镜像仓库描述
  • STARS:镜像仓库收藏数,表示该镜像仓库的受欢迎程度,类似于GitHub的stars。
  • OFFICIAL:表示是否为官方仓库,该标记为OK的镜像均由各软件的官方项目组创建和维护。由结果可知,Java这个镜像仓库是官方仓库。
  • AUTOMATED:表示是否是自动构建的镜像仓库。

2、下载镜像

docker pull java

执行该命令后,Docker默认从Docker Hub中的java仓库下载最新版本的java镜像。若镜像下载缓慢,可配置镜像加速器。该命令还可指定想要下载的镜像标签及Docker Registry地址,例如:

docker pull reg.itmuch.com/java:7

3、列出镜像

docker images 

上述命令可列出已下载到本地的镜像,执行命令后,将会看到如下表格:

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
java                latest              d23bdf5b1b1b        14 months ago       643MB

该表格包含了5列,含义如下:

  • REPOSITORY:镜像所属仓库名称。
  • TAG:镜像标签。默认是latest,表示最新。
  • IMAGE ID:镜像ID,表示镜像唯一标识。
  • CREATED:镜像创建时间。
  • SIZE:镜像大小。

4、删除本地镜像

docker rmi java

表示删除java这个镜像。

docker rmi -f $(docker images)

表示删除所有镜像
-f参数表示强制删除。

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

删除本地仓库里< none >的镜像,需先将现在运行的容器先删除docker rm -f $(docker ps -a -q)


二、Docker容器常用命令

1、新建并启动容器

使用以下docker run命令可新建并启动一个容器。

docker run

该命令是最常用的命令,它有很多选项,可使用docker run –help 查看选项。

$ 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
      --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
      --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 string                 Connect a container to a network (default "default")
      --network-alias list             Add network-scoped alias for the container
      --no-healthcheck                 Disable any container-specified HEALTHCHECK
      --oom-kill-disable               Disable OOM Killer
      --oom-score-adj int              Tune host's OOM preferences (-1000 to 1000)
      --pid string                     PID namespace to use
      --pids-limit int                 Tune container pids limit (set -1 for unlimited)
      --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
      --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

常用的选项有:

  • -d选项:表示后台运行
  • -P选项:随机端口映射
  • -p选项:指定端口映射,有以下四种格式。
    • ip:hostPort:containerPort
    • ip::containerPort
    • hostPort:containerPort
    • containerPort

示例:

docker run -d -p 91:80 nginx

-d #后台运行
-p 宿主机端口:容器端口 #开放容器端口到宿主机端口

访问http://Docker 宿主机 IP:91/,将会看到nginx的欢迎页面。

2、列出容器

使用docker ps命令可列出运行中的容器。执行该命令后,可看到类似于如下的表格。

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                NAMES
bbf25d18d4fb        nginx               "nginx -g 'daemon of…"   5 minutes ago       Up 5 minutes        0.0.0.0:91->80/tcp   gallant_ride

如需列出所有容器(包括已停止的容器),可使用-a参数。
该表格包含了7列,含义如下:

  • CONTAINER ID:表示容器ID。
  • IMAGE:表示镜像名称。
  • COMMAND:表示启动容器时运行的命令
  • CREATED:表示容器的创建时间。
  • STATUS:表示容器的运行状态。Up表示运行中,Exited表示已停止。
  • PORTS:表示容器对外的端口号。
  • NAMES:表示容器名称。该名称默认由Docker自动生成,也可使用docker run命令的–name选项自行指定。

3、停止容器

docker stop 容器ID/容器名称 

4、强制停止容器

docker kill 容器ID/容器名称

5、启动已停止的容器

使用docker run命令,即可新建并启动一个容器。对于已停止的容器,可使用docker start命令来启动。例如:

docker start 容器ID/容器名称

6、重启容器
可使用docker restart 命令来重启容器。该命令实际上是先执行了docker stop命令,然后执行了docker start命令。

7、进入容器
某场景下,可能需要进入运行中的容器。

docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
docker exec -it 0f2f3885c9a0 /bin/bash

进入该容器并开启一个bash。

8、删除容器

使用docker rm命令即可删除指定容器。

docker rm 容器ID/容器名称

该命令只能删除已停止的容器,如需删除正在运行的容器,可使用-f参数。

docker rm -f $(docker ps -a -q)

删除所有容器。

9、创建容器

有时候我们需要创建一个容器,但并不马上启动它,后面需要时,以start启动

docker create -it nginx
0151b61fbde63c8b9501e4d79652ea605bd1bc7cef79f22a68eca3ebadf3625a

上述命令执行完时,返回了自动创建好的容器ID。也可以指定–name指定容器名称创建,更多选项查看–help。

10、暂停容器

# 暂停一个容器,方便 commit
docker pause CONTAINER

11、继续暂停的容器

# 继续暂停的容器
docker unpause CONTAINER

12、查看容器或者镜像的详细信息

# 查看容器或者镜像的详细信息
docker inspect [OPTIONS] NAME|ID [NAME|ID...]

docker inspect NAME|ID
docker inspect --format "{{.State.Pid}}" NAME|ID
docker inspect --format '{{ .NetworkSettings.IPAddress }}' NAME|ID

拓展:

# 提交指定容器为镜像,默认 commit 是暂停状态
-a, –author=”” Author (e.g., “John Hannibal Smith [email protected]”)
-m, –message=”” Commit message
-p, –pause=true Pause container during commit
docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]


# 输出指定容器日志信息
-f, –follow=false Follow log output
# 类似 tail -f
-t, –timestamps=false Show timestamps
–tail=”allOutput the specified number of lines at the end of logs (defaults to all logs)
docker logs CONTAINER

三、Docker 命令帮助

docker command

Commands:
    attach    Attach to a running container                 # 当前 shell 下 attach 连接指定运行镜像
    build     Build an image from a Dockerfile              # 通过 Dockerfile 定制镜像
    commit    Create a new image from a container's changes # 提交当前容器为新的镜像
    cp        Copy files/folders from the containers filesystem to the host path
              # 从容器中拷贝指定文件或者目录到宿主机中
    create    Create a new container                        # 创建一个新的容器,同 run,但不启动容器
    diff      Inspect changes on a container's filesystem   # 查看 docker 容器变化
    events    Get real time events from the server          # 从 docker 服务获取容器实时事件
    exec      Run a command in an existing container        # 在已存在的容器上运行命令
    export    Stream the contents of a container as a tar archive
              # 导出容器的内容流作为一个 tar 归档文件[对应 import ]
    history   Show the history of an image                  # 展示一个镜像形成历史
    images    List images                                   # 列出系统当前镜像
    import    Create a new filesystem image from the contents of a tarball
              # 从tar包中的内容创建一个新的文件系统映像[对应 export]
    info      Display system-wide information               # 显示系统相关信息
    inspect   Return low-level information on a container   # 查看容器详细信息
    kill      Kill a running container                      # kill 指定 docker 容器
    load      Load an image from a tar archive              # 从一个 tar 包中加载一个镜像[对应 save]
    login     Register or Login to the docker registry server
              # 注册或者登陆一个 docker 源服务器
    logout    Log out from a Docker registry server         # 从当前 Docker registry 退出
    logs      Fetch the logs of a container                 # 输出当前容器日志信息
    port      Lookup the public-facing port which is NAT-ed to PRIVATE_PORT
              # 查看映射端口对应的容器内部源端口
    pause     Pause all processes within a container        # 暂停容器
    ps        List containers                               # 列出容器列表
    pull      Pull an image or a repository from the docker registry server
              # 从docker镜像源服务器拉取指定镜像或者库镜像
    push      Push an image or a repository to the docker registry server
              # 推送指定镜像或者库镜像至docker源服务器
    restart   Restart a running container                   # 重启运行的容器
    rm        Remove one or more containers                 # 移除一个或者多个容器
    rmi       Remove one or more images
              # 移除一个或多个镜像[无容器使用该镜像才可删除,否则需删除相关容器才可继续或 -f 强制删除]
    run       Run a command in a new container
              # 创建一个新的容器并运行一个命令
    save      Save an image to a tar archive                # 保存一个镜像为一个 tar 包[对应 load]
    search    Search for an image on the Docker Hub         # 在 docker hub 中搜索镜像
    start     Start a stopped containers                    # 启动容器
    stop      Stop a running containers                     # 停止容器
    tag       Tag an image into a repository                # 给源中镜像打标签
    top       Lookup the running processes of a container   # 查看容器中运行的进程信息
    unpause   Unpause a paused container                    # 取消暂停容器
    version   Show the docker version information           # 查看 docker 版本号
    wait      Block until a container stops, then print its exit code
              # 截取容器停止时的退出状态值
Run 'docker COMMAND --help' for more information on a command.

docker option

Usage of docker:
  --api-enable-cors=false                Enable CORS headers in the remote API                      # 远程 API 中开启 CORS 头
  -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
                                         # 和 -b 选项不兼容,具体没有测试过
  -d, --daemon=false                     Enable daemon mode                                         # daemon 模式
  -D, --debug=false                      Enable debug mode                                          # debug 模式
  --dns=[]                               Force docker to use specific DNS servers                   # 强制 docker 使用指定 dns 服务器
  --dns-search=[]                        Force Docker to use specific DNS search domains            # 强制 docker 使用指定 dns 搜索域
  -e, --exec-driver="native"             Force the docker runtime to use a specific exec driver     # 强制 docker 运行时使用指定执行驱动器
  --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                    # daemon 模式下 docker 指定绑定方式[tcp or 本地 socket]
                                           specified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd.
  --icc=true                             Enable inter-container communication                       # 跨容器通信
  --insecure-registry=[]                 Enable insecure communication with specified registries (no certificate verification for HTTPS and enable HTTP fallback) (e.g., localhost:5000 or 10.20.0.0/16)
  --ip="0.0.0.0"                         Default IP address to use when binding container ports     # 指定监听地址,默认所有 ip
  --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                 # 添加对应 iptables 规则
  --mtu=0                                Set the containers network MTU                             # 设置网络 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                            # 指定 pid 文件位置
  --registry-mirror=[]                   Specify a preferred Docker registry mirror
  -s, --storage-driver=""                Force the docker runtime to use a specific storage driver  # 强制 docker 运行时使用指定存储驱动
  --selinux-enabled=false                Enable selinux support                                     # 开启 selinux 支持
  --storage-opt=[]                       Set storage driver options                                 # 设置存储驱动选项
  --tls=false                            Use TLS; implied by tls-verify flags                       # 开启 tls
  --tlscacert="/root/.docker/ca.pem"     Trust only remotes providing a certificate signed by the CA given here
  --tlscert="/root/.docker/cert.pem"     Path to TLS certificate file                               # tls 证书文件位置
  --tlskey="/root/.docker/key.pem"       Path to TLS key file                                       # tls key 文件位置
  --tlsverify=false                      Use TLS and verify the remote (daemon: verify client, client: verify daemon) # 使用 tls 并确认远程控制主机
  -v, --version=false                    Print version information and quit   

猜你喜欢

转载自blog.csdn.net/u012834750/article/details/79890125
今日推荐