docker常用命令

man docker

NAME

docker - Docker image and container command line interface

SYNOPSIS

docker [OPTIONS] COMMAND [ARG...]

docker [--help|-v|--version]

DESCRIPTION

docker is a client for interacting with the daemon (see dockerd(8)) through the CLI.

The Docker CLI has over 30 commands. The commands are listed below and each has its own man page which explain usage and

arguments.

To see the man page for a command run man docker <command>.

docker有超过30个命令,每一个命令都有自己的man手册,使用man docker <command>来查询对应的语法

docker help可以查看docker语法的概览

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

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 #当前 shell 下 attach 连接指定运行镜像

build Build an image from a Dockerfile # 通过 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 # 创建一个新的容器,同 run,但不启动容器

diff Inspect changes to files or directories on a container's filesystem # 查看 docker 容器变化

events Get real time events from the server    # 从 docker 服务获取容器实时事件

exec Run a command in a running container # 在已存在的容器上运行命令

export Export a container's filesystem as a tar archive # 导出容器的内容流作为一个 tar 归档文件[对应 import ]

history Show the history of an image # 展示一个镜像形成历史

images List images # 列出系统当前镜像

import Import the contents from a tarball to create a filesystem image

# 从tar包中的内容创建一个新的文件系统映像[对应export]

info Display system-wide information #查看系统级别的信息

inspect Return low-level information on Docker objects     # 查看容器详细信息

kill Kill one or more running containers    # kill 指定 docker 容器

load Load an image from a tar archive or STDIN # 从一个 tar 包中加载一个镜像[对应 save]

login Log in to a Docker registry     # 注册或者登陆一个 docker 源服务器

logout Log out from a Docker registry    # 从当前 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    # 从docker镜像源服务器拉取指定镜像或者库镜像

push Push an image or a repository to a registry    # 推送指定镜像或者库镜像至docker源服务器

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) # 保存一个镜像为一个 tar 包[对应 load]

search Search the Docker Hub for images    # 在 docker hub 中搜索镜像

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 #查看docker版本信息

wait Block until one or more containers stop, then print their exit codes    # 截取容器停止时的退出状态值

 

Run 'docker COMMAND --help' for more information on a command.

镜像命令

[root@localhost ~]# docker image help

 

Usage:    docker image COMMAND

 

Manage images

 

Commands:

build Build an image from a Dockerfile

history Show the history of an image

import Import the contents from a tarball to create a filesystem image

inspect Display detailed information on one or more images

load Load an image from a tar archive or STDIN

ls List images

prune Remove unused images

pull Pull an image or a repository from a registry

push Push an image or a repository to a registry

rm Remove one or more images

save Save one or more images to a tar archive (streamed to STDOUT by default)

tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE

 

Run 'docker image COMMAND --help' for more information on a command.

docker images 列出镜像

REPOSITORY:表示镜像的仓库源

TAG:镜像的标签

IMAGE ID:镜像ID

CREATED:镜像创建时间

SIZE:镜像大小,只表示了该镜像的逻辑体积大小,相同的镜像层本地只会存储一份

参数:

  • -a 列出所有镜像(包括中间层)
  • -q 只显示镜像ID
  • --digests[=false] 显示镜像的摘要信息
  • --no-trunc[=false] 显示镜像的完整信息

docker search 搜索镜像(docker hub)

在docker hub上搜索匹配的镜像。

输出显示:名字、描述(默认截断的)、星标数、是否官方、是否是自动化的

最多显示25个搜索结果

过滤条件:

Filter output based on these conditions:

- stars=<numberOfStar>

- is-automated=(true|false)

- is-official=(true|false)

参数:

  • -f, --filter=

Filter output based on conditions provided #加上面的过滤条件

  • --format=""

Pretty-print search using a Go template

  • -h, --help[=false]

help for search

  • --limit=25

Max number of search results #修改最大搜索结果

  • --no-trunc[=false] 显示完整描述

Don't truncate output

docker pull 镜像名 下载镜像

举例:docker pull nginx

默认使用latest标签下载最新版

如果想要下载某个版本,需要到https://hub.docker.com/上搜索nginx,查看可用标签,使用docker pull nginx:1.19-perl等命令

严格的将,镜像的名称中还应该添加仓库地址作为前缀,只是默认使用的是官方的docker hub服务,该前缀可以省略

如果从非官方的仓库下载,则需要在镜像名前指定完整的仓库地址

有时候需要使用镜像代理服务来加速docker镜像的获取过程,参考https://www.cnblogs.com/jeancheng/p/13196685.html

 

 

查看镜像

docker rmi [OPTIONS] IMAGE [IMAGE...] 删除镜像

[root@localhost system]# docker rmi --help

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

Remove one or more images

Options:

-f, --force Force removal of the image

--no-prune Do not delete untagged parents

删除上面下载的1.19版本的nginx

查看镜像

删除所有镜像:docker rmi -f $(docker images -q)

docker tag为本地镜像添加标签

[root@localhost system]# docker tag --help

Usage:    docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]

Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE

docker inspect 查看镜像或容器的信息

[root@localhost system]# 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

-s, --size Display total file sizes if the type is container

--type string Return JSON for specified type

docker history 显示一个镜像的形成历史,每一层是什么,列出各层的创建信息

[root@localhost system]# docker history --help

Usage:    docker history [OPTIONS] IMAGE

Show the history of an image

Options:

--format string Pretty-print images using a Go template

-H, --human Print sizes and dates in human readable format (default true)

--no-trunc Don't truncate output

-q, --quiet Only show numeric IDs

docker commit 提交容器副本成为新的镜像

[root@localhost ~]# 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)

docker build根据dockerfile文件生成镜像

[root@localhost ~]# docker build --help

Usage:    docker build [OPTIONS] PATH | URL | - #不要忘了path

Build an image from a Dockerfile

Options:

--add-host list Add a custom host-to-IP mapping (host:ip)

--build-arg list Set build-time variables

--cache-from strings Images to consider as cache sources

--cgroup-parent string Optional parent cgroup for the container

--compress Compress the build context using gzip

--cpu-period int Limit the CPU CFS (Completely Fair Scheduler) period

--cpu-quota int Limit the CPU CFS (Completely Fair Scheduler) quota

-c, --cpu-shares int CPU shares (relative weight)

--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)

--disable-content-trust Skip image verification (default true)

-f, --file string Name of the Dockerfile (Default is 'PATH/Dockerfile') #指定dockerfile文件内容

--force-rm Always remove intermediate containers

--iidfile string Write the image ID to the file

--isolation string Container isolation technology

--label list Set metadata for an image

-m, --memory bytes Memory limit

--memory-swap bytes Swap limit equal to memory plus swap: '-1' to enable unlimited swap

--network string Set the networking mode for the RUN instructions during build (default "default")

--no-cache Do not use cache when building the image

-o, --output stringArray Output destination (format: type=local,dest=path)

--platform string Set platform if server is multi-platform capable

--progress string Set type of progress output (auto, plain, tty). Use plain to show container output (default "auto")

--pull Always attempt to pull a newer version of the image

-q, --quiet Suppress the build output and print image ID on success

--rm Remove intermediate containers after a successful build (default true)

--secret stringArray Secret file to expose to the build (only if BuildKit enabled): id=mysecret,src=/local/secret

--security-opt strings Security options

--shm-size bytes Size of /dev/shm

--squash Squash newly built layers into a single new layer

--ssh stringArray SSH agent socket or keys to expose to the build (only if BuildKit enabled) (format: default|<id>[=<socket>|<key>[,<key>]])

--stream Stream attaches to server to negotiate build context

-t, --tag list Name and optionally a tag in the 'name:tag' format #指定生成的镜像名与标签

--target string Set the target build stage to build.

--ulimit ulimit Ulimit options (default [])

[root@localhost docker]# docker build -f /docker/dockerfile -t hjc/centos

docker save 保存镜像到tar包

[root@localhost system]# docker save --help

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

Save one or more images to a tar archive (streamed to STDOUT by default)

Options:

-o, --output string Write to a file, instead of STDOUT

举例:

[root@localhost ~]# docker save -o nginx.v1.tar nginx:v1

[root@localhost ~]# ll |grep nginx

-rw-------. 1 root root 136338432 Jul 3 18:08 nginx.v1.tar

docker load 从tar包导入镜像文件

[root@localhost ~]# docker load --help

Usage:    docker load [OPTIONS]

Load an image from a tar archive or STDIN

Options:

-i, --input string Read from tar archive file, instead of STDIN

-q, --quiet Suppress the load output

容器命令

[root@localhost ~]# docker container help

Usage:    docker container COMMAND

Manage containers

Commands:

attach Attach local standard input, output, and error streams to a running container

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

exec Run a command in a running container

export Export a container's filesystem as a tar archive

inspect Display detailed information on one or more containers

kill Kill one or more running containers

logs Fetch the logs of a container

ls List containers

pause Pause all processes within one or more containers

port List port mappings or a specific mapping for the container

prune Remove all stopped containers

rename Rename a container

restart Restart one or more containers

rm Remove one or more containers

run Run a command in a new container

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

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

wait Block until one or more containers stop, then print their exit codes

 

Run 'docker container COMMAND --help' for more information on a command.

以centos为例

先下载centos image

创建容器

docker create 创建容器,但不运行

[root@localhost ~]# docker create --help

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

Create a new container

 

docker start 启动停止的容器

[root@localhost ~]# docker start -h

Flag shorthand -h has been deprecated, please use --help

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

Start one or more stopped containers

Options:

-a, --attach Attach STDOUT/STDERR and forward signals

--checkpoint string Restore from this checkpoint

--checkpoint-dir string Use a custom checkpoint storage directory

--detach-keys string Override the key sequence for detaching a container

-i, --interactive Attach container's STDIN

docker restart 重启容器

[root@localhost ~]# docker restart -h

Flag shorthand -h has been deprecated, please use --help

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

Restart one or more containers

Options:

-t, --time int Seconds to wait for stop before killing the container (default 10)

 

docker run 新建并启动容器,等价于先create,在start

[root@localhost ~]# docker run --help

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

Run a command in a new container

参数:

-d, --detach=true|false #容器后台运行,返回容器ID

Detached mode: run the container in the background and print the new container ID. The default is false.

-h, --hostname="" #设置容器主机名

Container host name

-i, --interactive=true|false 以交互式模式运行

Keep STDIN open even if not attached. The default is false.

--name="" #为容器指定一个名字

Assign a name to the container

--network=type #选择网络模式

-P, --publish-all=true|false #随机端口映射

Publish all exposed ports to random ports on the host interfaces. The default is false.

-p, --publish ip:[hostPort]:containerPort | [hostPort:]containerPort #指定端口映射

Publish a container's port, or range of ports, to the host.

-t, --tty=true|false #为容器分配一个伪终端

Allocate a pseudo-TTY. The default is false.    

-i 交互式运行

-t 分配一个伪终端

-it 正常交互,类似console

-d 容器后台运行

docker ps -a 进行查看, 会发现容器已经退出

很重要的要说明的一点: Docker容器后台运行,就必须有一个前台进程.

容器运行的命令如果不是那些一直挂起的命令(比如运行top,tail),就是会自动退出的。

这个是docker的机制问题,比如你的web容器,我们以nginx为例,正常情况下,我们配置启动服务只需要启动响应的service即可。

例如service nginx start

但是,这样做,nginx为后台进程模式运行,就导致docker前台没有运行的应用,

这样的容器后台启动后,会立即自杀因为他觉得他没事可做了.

所以,最佳的解决方案是,将你要运行的程序以前台进程的形式运行

[root@localhost ~]# docker run -d --network=host -p 8888:8080 --name="tomcat" tomcat:8.5.32

WARNING: Published ports are discarded when using host network mode

停止容器

docker pause 暂停一个容器

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

Usage:    docker pause CONTAINER [CONTAINER...]

Pause all processes within one or more containers

docker unpause 使暂停的容器恢复运行

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

Usage:    docker unpause CONTAINER [CONTAINER...]

Unpause all processes within one or more containers

docker stop 停止正在运行的容器(正常关闭容器)

[root@localhost ~]# docker stop -h

Flag shorthand -h has been deprecated, please use --help

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

Stop one or more running containers

Options:

-t, --time int Seconds to wait for stop before killing it (default 10)

docker kill 强制杀掉正在运行的容器

[root@localhost ~]# docker kill --help

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

Kill one or more running containers

Options:

-s, --signal string Signal to send to the container (default "KILL")

退出容器

ctrl+d或者exit 停止容器并退出

ctrl+p+q 不停止容器退出

 

进入容器

docker attach进入容器

[root@localhost ~]# 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 #指定退出attach模式的快捷键

--no-stdin Do not attach STDIN #是否关闭标准输入,默认保持打开

--sig-proxy Proxy all received signals to the process (default true)

多个窗口同时attach到一个容器时,所有窗口都会同步显示,当某个窗口因命令堵塞时,其他窗口也会堵塞

 

docker exec 在运行的容器中执行命令

[root@localhost ~]# 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 #打开标准输入接受用户输入命令,默认为false

--privileged Give extended privileges to the command #是否给命令最高权限

-t, --tty Allocate a pseudo-TTY #分配伪终端,默认为false

-u, --user string Username or UID (format: <name|uid>[:<group|gid>]) #执行命令的用户名或ID

-w, --workdir string Working directory inside the container

通过exec -it container /bin/bash对容器执行操作是最为推荐的方式

删除容器

docker rm 删除容器

[root@localhost ~]# 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) #强制删除正在运行的容器

-l, --link Remove the specified link

-v, --volumes Remove anonymous volumes associated with the container #删除容器挂载的数据卷

删除已经停止运行的容器centos2

删除正在运行的容器centos3,使用-f参数

docker rm $(docker ps -aq) 删除所有容器

导入和导出容器

实际上,既可以使用docker load命令来导入镜像存储文件到本地镜像库,也可以使用docker import命令来导入一个容器快照到本地镜像库

这两者的区别在于容器快照文件将丢弃所有的历史数据和元数据信息(即仅保存容器当时的快照状态);而镜像存储文件将保存完整的记录,体积更大。此外,从容器快照文件导入时可以重新指定标签等元数据信息。

docker export 导出容器为tar包

[root@localhost ~]# docker export --help

Usage:    docker export [OPTIONS] CONTAINER

Export a container's filesystem as a tar archive

Options:

-o, --output string Write to a file, instead of STDOUT

docker import 导入tar包为镜像

[root@localhost ~]# docker import --help

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

Import the contents from a tarball to create a filesystem image

Options:

-c, --change list Apply Dockerfile instruction to the created image

-m, --message string Set commit message for imported image

--platform string Set platform if server is multi-platform capable

查看容器

docker ps列出容器

[root@localhost ~]# docker ps -h

Flag shorthand -h has been deprecated, please use --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) #显示最近创建的N个容器

-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

docker top 显示容器中运行的进程

[root@localhost ~]# docker top --help

Usage:    docker top CONTAINER [ps OPTIONS]

Display the running processes of a container

 

docker stats 显示容器资源统计信息

[root@localhost ~]# docker stats --help

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

Display a live stream of container(s) resource usage statistics

Options:

-a, --all Show all containers (default shows just running) #输出所有容器的统计信息,默认只显示运行中的

--format string Pretty-print images using a Go template #格式化输出信息

--no-stream Disable streaming stats and only pull the first result #不持续输出,默认会自动更新实时结果

--no-trunc Do not truncate output #不截断输出信息

docker logs 查看容器日志

[root@localhost ~]# 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 #跟随最新的日志打印,容器的console输出,或者标准输出

--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)#输出某个时间之前的日志

docker port 查看容器端口映射

[root@localhost ~]# docker port --help

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

List port mappings or a specific mapping for the container

其他命令

docker cp 在宿主机和容器之间拷贝数据

[root@localhost ~]# 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) #打包模式,复制文件会带有原始的UID/GID信息

-L, --follow-link Always follow symbol link in SRC_PATH #跟随软连接。当原路径为软连接时,默认只复制链接信息,使用该选项会复制链接的目标内容

docker update 更新容器的配置

[root@localhost ~]# docker update --help

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

Update configuration of one or more containers

Options:

--blkio-weight uint16 Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)

--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 the CPU real-time period in microseconds

--cpu-rt-runtime int Limit the 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)

--kernel-memory bytes Kernel memory limit

-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

--pids-limit int Tune container pids limit (set -1 for unlimited)

--restart string Restart policy to apply when a container exits

问题:

1、桥接模式下,宿主机无法访问docker服务

启动tomcat容器

访问8888端口,报错

[root@localhost ~]# curl -L localhost:8888

curl: (56) Recv failure: Connection reset by peer

解决方案:删除并新建docker网桥

[root@localhost ~]# docker stop tomcat-1

tomcat-1

[root@localhost ~]# systemctl stop docker

[root@localhost ~]# ip a

[root@localhost ~]# ip link set dev docker0 down

[root@localhost ~]# brctl delbr docker0

[root@localhost ~]# ip a

[root@localhost ~]# brctl addbr docker0

[root@localhost ~]# ip a

[root@localhost ~]# ip link set dev docker0 up

[root@localhost ~]# ip a

启动docker服务,重新创建tomcat容器

原文地址:https://www.cnblogs.com/jeancheng/p/13205550.html