docker常见命令汇总
直接输入命令,根据提示查看命令汇总:
zhangboming@zhangbomingdeMacBook-Pro ~ % docker
Usage: docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
Options:
--config string Location of client config files (default "/Users/zhangboming/.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 "/Users/zhangboming/.docker/ca.pem")
--tlscert string Path to TLS certificate file (default "/Users/zhangboming/.docker/cert.pem")
--tlskey string Path to TLS key file (default "/Users/zhangboming/.docker/key.pem")
--tlsverify Use TLS and verify the remote
-v, --version Print version information and quit
Management Commands:
app* Docker App (Docker Inc., v0.9.1-beta3)
builder Manage builds
buildx* Build with BuildKit (Docker Inc., v0.5.1-docker)
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
scan* Docker Scan (Docker Inc., v0.5.0)
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 更深入的了解指定的 Docker 命令使用方法
一:镜像操作
docker search 关键字 搜索镜像
docker pull 从 Docker 仓库拉取镜像,Usage: docker pull [OPTIONS] NAME[:TAG|@DIGEST],DIGEST 表示通过哈希值拉取
docker pull mysql:8.0.43
docker pull mysql@sha256:6b17635bfb8e98e3c851b3963737ee0d3f99d7d639fed8fcaceaab7ee41049a9
docker images 列出本地存储的所有镜像
zhangboming@zhangbomingdeMacBook-Pro ~ % docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
tomcat latest bf4709e77b18 4 years ago 667MB
mysql 5.7.33 5f47254ca581 4 years ago 449MB
hello-world latest bf756fb1ae65 5 years ago 13.3kB
docker rmi 镜像名称或ID 删除一个或多个镜像
docker build 使用 Dockerfile 构建镜像,Usage: docker build [OPTIONS] PATH | URL | - ,其中 PATH 指包含 Dockerfile 的目录路径,URL 指向包含 Dockerfile 的远程存储库地址(如 Git 仓库),- 指的是从标准输入读取 Dockerfile
如下,从 /path/to/ 目录读取 Dockerfile 并构建一个名为 myimage:latest 的镜像,注意最后一个 . 是上下文路径
由于 docker 的运行模式是 C/S。我们本机是 C,docker 引擎是 S。实际的构建过程是在 docker 引擎下完成的,所以这个时候无法用到我们本机的文件。这就需要把我们本机的指定目录下的文件一起打包提供给 docker 引擎使用。
如果未说明最后一个参数,那么默认上下文路径就是 Dockerfile 所在的位置
注意:上下文路径下不要放无用的文件,因为会一起打包发送给 docker 引擎,如果文件过多会造成过程缓慢
docker build -f /path/to/Dockerfile -t myimage:latest .
docker save 将一个或多个 docker 镜像保存到一个 tar 归档文件中
保存单个镜像到文件
docker save -o myimage.tar myimage:latest
保存多个镜像到同一个文件
docker save -o multiple_images.tar myimage:latest anotherimage:latest
docker load 从由 docker save 命令生成的 tar 文件中加载 docker 镜像
docker load -i myimage.tar
docker tag 设置镜像标签,Usage: docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]
zhangboming@zhangbomingdeMacBook-Pro ~ % docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mysql <none> 9340b388320f 2 weeks ago 781MB
zhangboming@zhangbomingdeMacBook-Pro ~ % docker tag 9340b388320f mysql:temp
zhangboming@zhangbomingdeMacBook-Pro ~ % docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mysql temp 9340b388320f 2 weeks ago 781MB
docker push 将镜像推送到 Docker 仓库
二:容器操作
docker ps 列出当前正在运行的容器(-a 表示所有的容器包括已停止的容器也列出来)
zhangboming@zhangbomingdeMacBook-Pro ~ % docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a82798429e29 mysql:5.7.33 "docker-entrypoint.s…" 4 years ago Exited (255) 4 years ago 33060/tcp, 0.0.0.0:3307->3306/tcp mysql
docker run 启动一个新的容器并运行命令,Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
zhangboming@zhangbomingdeMacBook-Pro ~ % 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 # 后台运行容器,加了 -d 参数默认不会进入容器
-e, --env list Set environment variables # 设置环境变量,例如:docker run -e MY_ENV_VAR=my_value ubuntu
--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 # 例如:docker run -d --mount source=my-volume,target=/data my-image
--name string Assign a name to the container # 给容器指定一个名称
--network network Connect a container to a network # 指定容器的网络模式,例如:docker run --network host nginx(使用主机的网络模式运行 nginx 容器)
--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# 高权限运行模式,赋予容器几乎所有的宿主机权限,包括访问所有设备(/dev/sda、GPU、USB设备等)、内核模块、系统调用等,非常危险,应尽量使用更安全的替代方案
-p, --publish list Publish a container's port(s) to the host # 用法:宿主机IP:宿主机PORT:容器PORT,宿主机IP不写表示"0.0.0.0",宿主机PORT不写表示随机端口,容器PORT必须指定,可以同时对多个端口进行映射绑定,例如:docker run -d -p 5000:5000 web-image python app.py
-P, --publish-all Publish all exposed ports to random ports # 将容器内部使用的网络端口随机映射到宿主机上,如果连续启动多个容器的话,则下一个容器的端口默认是当前容器占用端口号+1,好处是由docker分配,宿主机端口不会冲突
--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") # 容器的重启策略(如 no、on-failure、always、unless-stopped),例如:docker run --restart always nginx(即使容器停止也会自动重启)
--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>]) # 指定用户,例如:docker run -u user123 ubuntu
--userns string User namespace to use
--uts string UTS namespace to use
-v, --volume list Bind mount a volume # 挂载卷,格式为 host_dir:container_dir 或者 volume_name:contailer_dir,例如:docker run -v /host/data:/container/data ubuntu
--volume-driver string Optional volume driver for the container
--volumes-from list Mount volumes from the specified container(s) # (数据卷的继承,例如:docker run -d --name my2 volumes-from my1 tomcat,即创建一个名为 my2 的容器,其绑定的容器卷和 my1 相同) <-- 不准确,应该是常用于备份数据文件,容器数据卷相关内容,回头补充
-w, --workdir string Working directory inside the container
$ docker run -it ubuntu /bin/bash
后台运行一个命名为 webserver 的 nginx 容器,将主机的 8080 端口映射到容器的 80 端口,并将主机的 /host/data 目录挂载到容器的 /data 目录
docker run -d -p 8080:80 -v /host/data:/data --name webserver nginx
-v 和 --mount 挂载的区别
① -v(--volume)主要用于简单挂载场景,适合快速挂载需求,例如开发调试时共享代码或配置文件。-v 支持 bind 和 volume 两种挂载类型,若宿主机目录不存在会自动创建。
docker run -d --name <容器名> -v <宿主机目录>:<容器目录>
docker run -d --name <容器名> -v <数据卷名>:<容器目录>
② --mount 支持更复杂的挂载需求(例如使用 tmpfs 临时存储),需要指定挂载类型或驱动选项。--mount 包含 bind、volume(默认) 和 tmpfs 三种挂载类型,通过 type 参数来改变挂载方式。若宿主机目录不存在,默认会报错。
docker run -d --name <容器名> --mount type=bind,source=<宿主机目录>,destination=<容器目录>
docker run -d --name <容器名> --mount type=volume,source=<数据卷名>,destination=<容器目录>
docker run -d --name <容器名> --mount type=tmpfs,destination=<容器目录>
对于匿名卷,source 参数可以省略
docker attach 允许你与容器的标准输入(stdin)、输出(stdout)和标准错误(stderr)进行交互
该命令会改变容器的状态,因为它将打开容器的终端并将其连接到当前终端,如果退出容器的shell,容器会停止运行。该命令通常用于调试和排除故障与 exec 命令存在区别,一般建议用 exec 命令
docker exec 在运行的容器中执行命令
zhangboming@zhangbomingdeMacBook-Pro ~ % 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 # 例如:docker exec -e MY_ENV_VAR=my_value my_container env(在运行中的 my_container 容器内执行 env 命令,并设置环境变量 MY_ENV_VAR 的值为 my_value)
--env-file list Read in a file of 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>]) # 以指定用户的身份运行命令,例如:docker exec -u user123 my_container whoami
-w, --workdir string Working directory inside the container # 指定命令的工作目录,例如:docker exec -w /app my_container pwd(在运行中的 my_container 容器内以 /app 目录为工作目录执行 pwd 命令)
进入容器的交互式终端 docker exec -it
zhangboming@zhangbomingdeMacBook-Pro ~ % docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a82798429e29 mysql:5.7.33 "docker-entrypoint.s…" 4 years ago Up 5 seconds 33060/tcp, 0.0.0.0:3307->3306/tcp mysql
zhangboming@zhangbomingdeMacBook-Pro ~ % docker exec -it a82798429e29 /bin/bash
root@a82798429e29:/#
docker stop 停止一个或多个容器
docker start 启动已停止的容器
docker restart 重启一个或多个容器
docker rm 删除一个或多个容器
docker logs [OPTIONS] 容器 查看容器的日志,具体 [OPTIONS] 查阅 docker logs --help
docker inspect NAME|ID 获取容器或镜像的详细信息
docker top 查看容器内部运行的进程
zhangboming@zhangbomingdeMacBook-Pro ~ % docker top a82798429e29
UID PID PPID C STIME TTY TIME CMD
999 2861 2834 3 03:33 ? 00:00:00 mysqld
三:卷与网络
docker network ls 列出所有 Docker 网络
docker port 容器ID或容器名 查看指定容器的某个确定端口映射到宿主机的端口号,以下为将本机3307端口映射到容器内的3306
zhangboming@zhangbomingdeMacBook-Pro ~ % docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a82798429e29 mysql:5.7.33 "docker-entrypoint.s…" 4 years ago Up 11 hours 33060/tcp, 0.0.0.0:3307->3306/tcp mysql
zhangboming@zhangbomingdeMacBook-Pro ~ % docker port a82798429e29
3306/tcp -> 0.0.0.0:3307
docker volume ls 列出所有 Docker 卷
zhangboming@zhangbomingdeMacBook-Pro ~ % docker volume ls
DRIVER VOLUME NAME
local 53f09c5247555185d53eb2ce27c6053dd1c7ad9755206c7b9e92b7c41a6013b5
local mysql_data
local mysqldata
zhangboming@zhangbomingdeMacBook-Pro ~ % docker volume ls -q --filter 'name=mysql_data'
mysql_data
docker volume rm <volume> 删除指定的卷
docker volume prune 删除未使用的卷
docker volume inspect <volume> 显示卷的详细信息
docker volume create <volume> 创建一个新的卷
zhangboming@zhangbomingdeMacBook-Pro ~ % docker volume create --help
Usage: docker volume create [OPTIONS] [VOLUME]
Create a volume
Options:
-d, --driver string Specify volume driver name (default "local")
--label list Set metadata for a volume # 为卷添加标签
-o, --opt map Set driver specific options (default map[])
zhangboming@zhangbomingdeMacBook-Pro ~ % docker volume create --label "type=db" mysql_data
mysql_data
四:Docker-Compose
docker-compose up 启动多容器应用(从 docker-compose.yml 文件)
docker-compose down 停止并删除由 docker-compose 启动的容器、网络等
五:其他
docker info 显示 Docker 系统的详细信息
docker version 显示 Docker 客户端和守护进程的版本信息
docker stats 显示容器的实时资源使用情况
六:docker 命令别名
如果觉得 docker 命令冗长,可以在 linux 系统中创建 docker 命令的别名
① 修改/root/.bashrc文件 vi /root/.bashrc,内容如下
# .bashrc
# User specific aliases and functions
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
alias dps='docker ps --format "table {{.ID}}\t{{.Image}}\t{{.Ports}}\t{{.Status}}\t{{.Names}}"'
alias dis='docker images'
# Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
② 然后,执行命令使别名生效 source /root/.bashrc

浙公网安备 33010602011771号