Docker的常用命令
一、安装Nginx
在介绍Docker命令之前,先通过Docker安装一个Nginx,这样后面的命令才有参照物。
一、配置容器镜像下载地址
Docker在没有任何配置的情况下,默认是从Docker Hub公共仓库拉取镜像的,如果网络状况不好的话,很大概率会拉取失败,所以我们需要先配置容器镜像下载地址,这样它就不会上来就直接去Docker Hub拉取:
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
"registry-mirrors": [
"https://docker.m.daocloud.io",
"https://docker.rainbond.cc",
"https://docker.lmirror.top"
]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker
按照上图配置完成之后,执行 docker info命令查看是否配置成功

二、安装Nginx
第一步:拉取Nginx的镜像
# pull是拉取的意思,nginx是镜像名称,1.23是指定的版本
docker pull nginx:1.23
第二步:创建本地挂载目录
/mydata/nginx/conf:存放主配置文件nginx.conf/mydata/nginx/conf.d:存放站点配置文件(如default.conf)/mydata/nginx/html:存放网站静态文件/mydata/nginx/logs:存放访问日志和错误日志
mkdir -p /mydata/nginx/{conf,conf.d,html,logs}
第三步:创建一个临时容器,用于拷贝nginx配置文件到本地挂载目录
# docker run用于创建并运行容器,--name用于指定容器名,-d指的是后台运行,最后是指定镜像(容器创建模板)
docker run --name tmp-nginx -d nginx:1.23
第四步:拷贝配置文件
#将tmp-nginx容器内的nginx.conf拷贝到本地挂载目录conf下
docker cp tmp-nginx:/etc/nginx/nginx.conf /mydata/nginx/conf/
#将tmp-nginx容器内的default.conf文件拷贝到本地挂载目录conf.d下
docker cp tmp-nginx:/etc/nginx/conf.d/default.conf /mydata/nginx/conf.d/
第五步:删除临时容器
#停止正在运行的容器
docker stop tmp-nginx
#删除容器
docker rm tmp-nginx
第六步:正式创建容器
docker run --name nginx \
-d \
-p 80:80 \
-v /mydata/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
-v /mydata/nginx/conf.d/default.conf:/etc/nginx/conf.d/default.conf \
-v /mydata/nginx/html:/usr/share/nginx/html \
-v /mydata/nginx/logs:/var/log/nginx \
nginx:1.23
命令解释:
-d:后台运行;-p:将宿主机指定端口映射到容器的指定端口;-v:挂载本地目录到容器内路径,实现配置和数据的持久化;
最后:查看容器是否正常运行
#查询所有正在运行的容器
docker ps

二、Docker命令
我们可以执行 docker -h命令查看Docker的命令列表
Flag shorthand -h has been deprecated, use --help
Usage: docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
Common Commands:
run Create and run a new container from an image
exec Execute a command in a running container
ps List containers
build Build an image from a Dockerfile
bake Build from a file
pull Download an image from a registry
push Upload an image to a registry
images List images
login Authenticate to a registry
logout Log out from a registry
search Search Docker Hub for images
version Show the Docker version information
info Display system-wide information
Management Commands:
builder Manage builds
buildx* Docker Buildx
compose* Docker Compose
container Manage containers
context Manage contexts
image Manage images
manifest Manage Docker image manifests and manifest lists
network Manage networks
plugin Manage plugins
system Manage Docker
volume Manage volumes
Swarm Commands:
swarm Manage Swarm
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
events Get real time events from the server
export Export a container's filesystem as a tar archive
history Show the history of an image
import Import the contents from a tarball to create a filesystem image
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
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
rename Rename a container
restart Restart one or more containers
rm Remove one or more containers
rmi Remove one or more images
save Save one or more images to a tar archive (streamed to STDOUT by default)
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
wait Block until one or more containers stop, then print their exit codes
Global 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 string Daemon socket 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
Run 'docker COMMAND --help' for more information on a command.
For more help on how to use Docker, head to https://docs.docker.com/go/guides/
如果你想查看具体某个命令的用法和相关参数,可以执行 docker COMMAND --help命令
root@DESKTOP-0QJE53P:/mydata/nginx/conf.d# docker run --help
Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Create and run a new container from an image
Aliases:
docker container run, docker run
Options:
--add-host list Add a custom host-to-IP mapping (host:ip)
--annotation map Add an annotation to the container (passed through to the OCI runtime) (default map[])
-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 [])
--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-interval duration Time between running the check during the start period (ms|s|m|h) (default 0s)
--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 ip IPv4 address (e.g., 172.30.100.104)
--ip6 ip IPv6 address (e.g., 2001:db8::33)
--ipc string IPC mode to use
--isolation string Container isolation technology
-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")
-q, --quiet Suppress the pull output
--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 and its associated anonymous volumes 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 the container
--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 [])
--use-api-socket Bind mount Docker API socket and required auth
-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
一、docker run命令
该命令用于创建一个容器并且运行,比如前面创建Nginx容器的命令:
docker run --name nginx \
-d \
-p 80:80 \
-v /mydata/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
-v /mydata/nginx/conf.d/default.conf:/etc/nginx/conf.d/default.conf \
-v /mydata/nginx/html:/usr/share/nginx/html \
-v /mydata/nginx/logs:/var/log/nginx \
nginx:1.23
命令解释:
--name:指定容器名;-d:后台运行;-p:将宿主机指定端口映射到容器的指定端口;-v:挂载本地目录到容器内路径,实现配置和数据的持久化;nginx:1.23:镜像名:版本号;
二、docker ps命令
该命令用于查看当前的容器列表。
#查看当前正在运行的容器
docker ps
#查看所有的容器(包括不在运行的)
docker ps -a

- CONTAINER ID:容器的ID;
- IMAGE:容器创建使用的镜像;
- CREATED:创建时间;
- STATUS:容器当前状态,UP表示正在运行,Exited表示容器停止运行;
- PORTS:作了映射的端口;
- NAMES:容器名;
三、docker inspect命令
该命令用于获取容器或者镜像的详细信息。
- 查看容器的详细信息
root@DESKTOP-0QJE53P:/mydata/nginx/conf.d# docker inspect nginx
[
{
"Id": "77b4e1b9a28fd544d950d7c6c1cd82acd1bd6f78d088ac59785cadc23db3ed6d",
"Created": "2026-06-12T03:23:01.883858335Z",
"Path": "/docker-entrypoint.sh",
"Args": [
"nginx",
"-g",
"daemon off;"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 2094,
"ExitCode": 0,
"Error": "",
"StartedAt": "2026-06-12T03:23:01.949774702Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:f5747a42e3adcb3168049d63278d7251d91185bb5111d2563d58729a5c9179b0",
"ResolvConfPath": "/var/lib/docker/containers/77b4e1b9a28fd544d950d7c6c1cd82acd1bd6f78d088ac59785cadc23db3ed6d/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/77b4e1b9a28fd544d950d7c6c1cd82acd1bd6f78d088ac59785cadc23db3ed6d/hostname",
"HostsPath": "/var/lib/docker/containers/77b4e1b9a28fd544d950d7c6c1cd82acd1bd6f78d088ac59785cadc23db3ed6d/hosts",
"LogPath": "/var/lib/docker/containers/77b4e1b9a28fd544d950d7c6c1cd82acd1bd6f78d088ac59785cadc23db3ed6d/77b4e1b9a28fd544d950d7c6c1cd82acd1bd6f78d088ac59785cadc23db3ed6d-json.log",
"Name": "/nginx",
"RestartCount": 0,
"Driver": "overlayfs",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "",
"ExecIDs": null,
"HostConfig": {
"Binds": [
"/mydata/nginx/conf/nginx.conf:/etc/nginx/nginx.conf",
"/mydata/nginx/conf.d/default.conf:/etc/nginx/conf.d/default.conf",
"/mydata/nginx/html:/usr/share/nginx/html",
"/mydata/nginx/logs:/var/log/nginx"
],
"ContainerIDFile": "",
"LogConfig": {
"Type": "json-file",
"Config": {}
},
"NetworkMode": "bridge",
"PortBindings": {
"80/tcp": [
{
"HostIp": "",
"HostPort": "80"
}
]
},
"RestartPolicy": {
"Name": "no",
"MaximumRetryCount": 0
},
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": null,
"ConsoleSize": [
70,
280
],
"CapAdd": null,
"CapDrop": null,
"CgroupnsMode": "private",
"Dns": null,
"DnsOptions": [],
"DnsSearch": [],
"ExtraHosts": null,
"GroupAdd": null,
"IpcMode": "private",
"Cgroup": "",
"Links": null,
"OomScoreAdj": 0,
"PidMode": "",
"Privileged": false,
"PublishAllPorts": false,
"ReadonlyRootfs": false,
"SecurityOpt": null,
"UTSMode": "",
"UsernsMode": "",
"ShmSize": 67108864,
"Runtime": "runc",
"Isolation": "",
"CpuShares": 0,
"Memory": 0,
"NanoCpus": 0,
"CgroupParent": "",
"BlkioWeight": 0,
"BlkioWeightDevice": [],
"BlkioDeviceReadBps": [],
"BlkioDeviceWriteBps": [],
"BlkioDeviceReadIOps": [],
"BlkioDeviceWriteIOps": [],
"CpuPeriod": 0,
"CpuQuota": 0,
"CpuRealtimePeriod": 0,
"CpuRealtimeRuntime": 0,
"CpusetCpus": "",
"CpusetMems": "",
"Devices": [],
"DeviceCgroupRules": null,
"DeviceRequests": null,
"MemoryReservation": 0,
"MemorySwap": 0,
"MemorySwappiness": null,
"OomKillDisable": null,
"PidsLimit": null,
"Ulimits": [],
"CpuCount": 0,
"CpuPercent": 0,
"IOMaximumIOps": 0,
"IOMaximumBandwidth": 0,
"MaskedPaths": [
"/proc/acpi",
"/proc/asound",
"/proc/interrupts",
"/proc/kcore",
"/proc/keys",
"/proc/latency_stats",
"/proc/sched_debug",
"/proc/scsi",
"/proc/timer_list",
"/proc/timer_stats",
"/sys/devices/virtual/powercap",
"/sys/firmware"
],
"ReadonlyPaths": [
"/proc/bus",
"/proc/fs",
"/proc/irq",
"/proc/sys",
"/proc/sysrq-trigger"
]
},
"Storage": {
"RootFS": {
"Snapshot": {
"Name": "overlayfs"
}
}
},
"Mounts": [
{
"Type": "bind",
"Source": "/mydata/nginx/conf/nginx.conf",
"Destination": "/etc/nginx/nginx.conf",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
},
{
"Type": "bind",
"Source": "/mydata/nginx/conf.d/default.conf",
"Destination": "/etc/nginx/conf.d/default.conf",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
},
{
"Type": "bind",
"Source": "/mydata/nginx/html",
"Destination": "/usr/share/nginx/html",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
},
{
"Type": "bind",
"Source": "/mydata/nginx/logs",
"Destination": "/var/log/nginx",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
}
],
"Config": {
"Hostname": "77b4e1b9a28f",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts": {
"80/tcp": {}
},
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"NGINX_VERSION=1.23.4",
"NJS_VERSION=0.7.11",
"PKG_RELEASE=1~bullseye"
],
"Cmd": [
"nginx",
"-g",
"daemon off;"
],
"Image": "nginx:1.23",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": [
"/docker-entrypoint.sh"
],
"Labels": {
"maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
},
"StopSignal": "SIGQUIT"
},
"NetworkSettings": {
"SandboxID": "6c82477f3adc49f4ffefa66098d876f19da5bee7b031ba6843733c1eb3756ba5",
"SandboxKey": "/var/run/docker/netns/6c82477f3adc",
"Ports": {
"80/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "80"
},
{
"HostIp": "::",
"HostPort": "80"
}
]
},
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"DriverOpts": null,
"GwPriority": 0,
"NetworkID": "1820cf90f59214b6f2715207b4b5d56c295173fc74121a62bce54978c104a5c2",
"EndpointID": "b511aec1d0286be66b44d3f1ad22ccfa267dc13b7ef8cb70c484e02cb7f37729",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2",
"MacAddress": "ae:6b:21:4d:4f:c5",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"DNSNames": null
}
}
},
"ImageManifestDescriptor": {
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
"digest": "sha256:a97a153152fcd6410bdf4fb64f5622ecf97a753f07dcc89dab14509d059736cf",
"size": 1570,
"platform": {
"architecture": "amd64",
"os": "linux"
}
}
}
]
- 查看镜像的详细信息
root@DESKTOP-0QJE53P:/mydata/nginx/conf.d# docker inspect nginx:1.23
[
{
"Id": "sha256:f5747a42e3adcb3168049d63278d7251d91185bb5111d2563d58729a5c9179b0",
"RepoTags": [
"nginx:1.23"
],
"RepoDigests": [
"nginx@sha256:f5747a42e3adcb3168049d63278d7251d91185bb5111d2563d58729a5c9179b0"
],
"Created": "2023-05-23T08:51:38.011802405Z",
"Config": {
"ExposedPorts": {
"80/tcp": {}
},
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"NGINX_VERSION=1.23.4",
"NJS_VERSION=0.7.11",
"PKG_RELEASE=1~bullseye"
],
"Entrypoint": [
"/docker-entrypoint.sh"
],
"Cmd": [
"nginx",
"-g",
"daemon off;"
],
"Labels": {
"maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
},
"StopSignal": "SIGQUIT"
},
"Architecture": "amd64",
"Os": "linux",
"Size": 57002949,
"RootFS": {
"Type": "layers",
"Layers": [
"sha256:8cbe4b54fa88d8fc0198ea0cc3a5432aea41573e6a0ee26eca8c79f9fbfa40e3",
"sha256:5dd6bfd241b4f4d0bb0a784cd7cefe00829edce2fccb2fcad71244df6344abff",
"sha256:043198f57be0cb6dd81abe9dd01531faa8dd2879239dc3b798870c0604e1bb3c",
"sha256:2731b5cfb6163ee5f1fe6126edb946ef11660de5a949404cc76207bf8a9c0e6e",
"sha256:6791458b394218a2c05b055f952309afa42ec238b74d5165cf1e2ebe9ffe6a33",
"sha256:4d33db9fdf22934a1c6007dcfbf84184739d590324c998520553d7559a172cfb"
]
},
"Metadata": {
"LastTagTime": "2026-06-12T02:42:34.484952284Z"
},
"Descriptor": {
"mediaType": "application/vnd.docker.distribution.manifest.list.v2+json",
"digest": "sha256:f5747a42e3adcb3168049d63278d7251d91185bb5111d2563d58729a5c9179b0",
"size": 1862
},
"Identity": {
"Pull": [
{
"Repository": "docker.io/library/nginx"
}
]
}
}
]
四、docker exec命令
该命令用于在一个正在运行的容器中执行命令。比如我们需要进入容器容器调试容器、修改配置之类的,通常会执行如下命令:
docker exec -it <容器ID或名称> /bin/bash
-i(interactive):保持标准输入(STDIN)打开,即使没有连接。这让你能向容器发送指令。-t(tty):分配一个伪终端(pseudo-TTY)。这让你能看到类似 Linux 的命令提示符界面。/bin/bash:指定要在容器内运行的程序。对于大多数 Linux 镜像(如 Nginx, Ubuntu),通常是/bin/bash;如果是精简版镜像(如 Alpine),则可能是/bin/sh。
现在我们拿正在运行的Nginx容器来看,执行如下命令:
docker exec -it nginx /bin/bash


如果需要返回到原来的命令行界面,可以执行 exit命令。
五、docker stop命令
该命令用于关闭正在运行的容器,可以同时关闭多个。
root@DESKTOP-0QJE53P:/mydata/nginx/conf.d# docker stop nginx
nginx
如果正在运行的容器比较多,想把它们全部关闭的话一个个敲比较浪费时间,可以使用如下命令:
root@DESKTOP-0QJE53P:/mydata/nginx/conf.d# docker stop $(docker ps -q)
77b4e1b9a28f
docker ps前面说过了,是获取正在运行的容器列表,-q指的是只获取容器ID
六、docker start命令
该命令用于启动容器。
root@DESKTOP-0QJE53P:/mydata/nginx/conf.d# docker start nginx
nginx
七、docker top命令
该命令用于查看容器内的进程信息。
docker top nginx

八、docker rm命令
该命令用于删除容器。
docker rm <容器ID或名称>

浙公网安备 33010602011771号