跳到主要内容

Docker 基础命令

本章将介绍 Docker 最常用的命令,包括镜像操作和容器操作。掌握这些命令是使用 Docker 的基础。

Docker 命令结构

Docker 命令的基本格式:

docker [选项] 命令 [参数]

命令分类

分类命令说明
镜像管理docker image管理镜像
容器管理docker container管理容器
网络管理docker network管理网络
数据卷管理docker volume管理数据卷
系统管理docker system管理系统

镜像操作

搜索镜像

在 Docker Hub 搜索镜像:

# 搜索镜像
docker search nginx

# 限制结果数量
docker search --limit 5 nginx

# 过滤官方镜像
docker search --filter=is-official=true nginx

输出解释

NAME                  DESCRIPTION                                     STARS     OFFICIAL
nginx Official build of Nginx. 18000 [OK]
  • NAME:镜像名称
  • DESCRIPTION:镜像描述
  • STARS:收藏数量
  • OFFICIAL:是否为官方镜像

拉取镜像

从仓库下载镜像到本地:

# 拉取最新版本
docker pull nginx

# 拉取指定版本
docker pull nginx:1.24

# 拉取指定平台
docker pull --platform linux/arm64 nginx

# 拉取所有标签
docker pull -a nginx

镜像标签格式镜像名:标签

  • 不指定标签时默认使用 latest
  • 标签可以是版本号、操作系统等

镜像分层

Docker 镜像由多个只读层组成,每层代表 Dockerfile 中的一条指令。这种分层设计带来了几个好处:

  1. 共享基础层:多个镜像可以共享相同的基础层,节省存储空间
  2. 增量更新:只有变化的层需要重新构建和传输
  3. 缓存复用:构建时可以利用缓存,加快构建速度

查看镜像

列出本地镜像:

# 列出所有镜像
docker images
docker image ls

# 显示镜像 ID
docker images -q

# 显示镜像摘要
docker images --digests

# 过滤镜像
docker images --filter "dangling=true" # 显示悬空镜像
docker images --filter "reference=nginx"

# 格式化输出
docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}"

输出解释

REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
nginx latest 605c77e624dd 2 weeks ago 141MB
nginx 1.24 4cdc5dd7eaad 3 months ago 142MB
  • REPOSITORY:镜像仓库名
  • TAG:镜像标签
  • IMAGE ID:镜像唯一标识
  • CREATED:创建时间
  • SIZE:镜像大小

查看镜像详情

# 查看镜像详细信息
docker image inspect nginx

# 查看特定信息
docker image inspect --format='{{.Architecture}}' nginx
docker image inspect --format='{{.Size}}' nginx
docker image inspect --format='{{.Config.Cmd}}' nginx

查看镜像历史

# 查看镜像构建历史
docker history nginx

# 显示完整信息
docker history --no-trunc nginx

删除镜像

# 删除镜像
docker rmi nginx

# 强制删除(即使有容器使用)
docker rmi -f nginx

# 删除悬空镜像
docker image prune

# 删除所有未使用的镜像
docker image prune -a

# 批量删除
docker rmi nginx:latest nginx:1.24

悬空镜像:没有标签指向的镜像,通常由构建新镜像产生。当你用相同标签构建新镜像时,旧镜像就会变成悬空镜像。

导出和导入镜像

# 导出镜像为 tar 文件
docker save -o nginx.tar nginx:latest

# 导出多个镜像
docker save -o images.tar nginx:latest redis:latest

# 从 tar 文件导入镜像
docker load -i nginx.tar

# 从容器创建镜像
docker commit [容器ID] my-nginx:v1

# 带说明信息
docker commit -m "自定义 Nginx" -a "作者" [容器ID] my-nginx:v1

镜像标签

# 创建镜像标签
docker tag nginx:latest my-registry/nginx:v1

# 推送到私有仓库
docker push my-registry/nginx:v1

容器操作

创建并运行容器

# 基本运行
docker run nginx

# 后台运行
docker run -d nginx

# 指定名称
docker run -d --name my-nginx nginx

# 交互式运行
docker run -it ubuntu bash

# 端口映射
docker run -d -p 8080:80 nginx

# 多端口映射
docker run -d -p 8080:80 -p 8443:443 nginx

# 随机端口映射
docker run -d -P nginx

# 环境变量
docker run -d -e MYSQL_ROOT_PASSWORD=123456 mysql

# 多个环境变量
docker run -d -e VAR1=value1 -e VAR2=value2 nginx

# 从文件读取环境变量
docker run -d --env-file .env nginx

docker run 常用选项

选项说明
-d后台运行(detached 模式)
-i保持 STDIN 打开
-t分配伪终端
--name指定容器名称
-p端口映射(主机端口:容器端口)
-P随机端口映射
-v挂载数据卷
-e设置环境变量
--env-file从文件读取环境变量
--restart重启策略
--network指定网络
--rm容器退出后自动删除

容器重启策略

重启策略决定了容器退出时 Docker 是否自动重启它:

# 不自动重启(默认)
docker run -d --restart=no nginx

# 总是重启
docker run -d --restart=always nginx

# 除非手动停止,否则总是重启(推荐用于生产环境)
docker run -d --restart=unless-stopped nginx

# 失败时重启,最多重启 3 次
docker run -d --restart=on-failure:3 nginx

重启策略选择建议

  • 开发环境:使用 noon-failure
  • 生产环境:使用 unless-stoppedalways
  • 定时任务容器:使用 on-failure

查看容器

# 查看运行中的容器
docker ps
docker container ls

# 查看所有容器(包括已停止)
docker ps -a

# 只显示容器 ID
docker ps -q

# 显示容器大小
docker ps -s

# 过滤容器
docker ps --filter "name=nginx"
docker ps --filter "status=running"
docker ps --filter "ancestor=nginx"

# 格式化输出
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
docker ps --format "{{.Names}}: {{.Status}}"

状态说明

  • created:已创建,未启动
  • running:运行中
  • paused:已暂停
  • restarting:重启中
  • exited:已退出
  • dead:已死亡

容器操作

# 启动容器
docker start [容器名或ID]

# 停止容器
docker stop [容器名或ID]

# 重启容器
docker restart [容器名或ID]

# 暂停容器
docker pause [容器名或ID]

# 恢复容器
docker unpause [容器名或ID]

# 强制停止
docker kill [容器名或ID]

# 等待容器停止
docker wait [容器名或ID]

stop 和 kill 的区别

  • docker stop:发送 SIGTERM 信号,等待容器优雅退出(默认 10 秒),超时后发送 SIGKILL
  • docker kill:直接发送 SIGKILL 信号,强制终止容器

进入容器

# 执行命令
docker exec [容器名或ID] ls /app

# 进入交互终端
docker exec -it [容器名或ID] bash

# 以 root 用户进入
docker exec -it -u 0 [容器名或ID] bash

# 指定工作目录
docker exec -it -w /app [容器名或ID] bash

# 使用 attach 连接到容器主进程
docker attach [容器名或ID]
# 注意:Ctrl+C 会停止容器,Ctrl+P Ctrl+Q 退出但保持容器运行

exec 和 attach 的区别

  • exec:在容器中创建新进程,退出不影响容器
  • attach:连接到容器主进程(PID 1),退出可能导致容器停止

查看容器日志

# 查看日志
docker logs [容器名或ID]

# 实时跟踪日志
docker logs -f [容器名或ID]

# 显示最近 100 行
docker logs --tail 100 [容器名或ID]

# 显示时间戳
docker logs -t [容器名或ID]

# 查看指定时间段的日志
docker logs --since 2024-01-01 [容器名或ID]
docker logs --since 2h [容器名或ID]
docker logs --until 2024-01-02 [容器名或ID]

查看容器信息

# 查看容器详情
docker inspect [容器名或ID]

# 查看特定信息
docker inspect --format='{{.State.Status}}' [容器名或ID]
docker inspect --format='{{.NetworkSettings.IPAddress}}' [容器名或ID]
docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' [容器名或ID]

# 查看容器进程
docker top [容器名或ID]

# 查看容器资源使用
docker stats [容器名或ID]
docker stats --no-stream [容器名或ID]

# 查看容器端口映射
docker port [容器名或ID]

查看容器变更

# 查看容器文件系统变更
docker diff [容器名或ID]

输出说明:

  • A:新增文件
  • C:修改文件
  • D:删除文件

文件复制

# 从容器复制文件到主机
docker cp [容器名或ID]:/app/config.yml ./config.yml

# 从主机复制文件到容器
docker cp ./config.yml [容器名或ID]:/app/config.yml

# 复制目录
docker cp ./data [容器名或ID]:/app/

删除容器

# 删除已停止的容器
docker rm [容器名或ID]

# 强制删除运行中的容器
docker rm -f [容器名或ID]

# 删除所有停止的容器
docker container prune

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

# 删除容器及其关联的卷
docker rm -v [容器名或ID]

资源限制

内存限制

# 限制内存为 512MB
docker run -d --memory="512m" nginx

# 限制内存和交换内存
docker run -d --memory="512m" --memory-swap="1g" nginx

# 设置内存软限制
docker run -d --memory-reservation="256m" nginx

内存限制参数说明

  • --memory:硬限制,容器使用的内存不能超过此值
  • --memory-swap:内存 + 交换分区的总限制
  • --memory-reservation:软限制,系统内存紧张时会尝试限制到此值

CPU 限制

# 限制 CPU 配额为 0.5 个 CPU
docker run -d --cpus="1.5" nginx

# 指定 CPU 核心
docker run -d --cpuset-cpus="0,1" nginx

# 设置 CPU 权重(默认 1024)
docker run -d --cpu-shares=512 nginx

CPU 限制参数说明

  • --cpus:限制容器可以使用的 CPU 核心数
  • --cpuset-cpus:绑定到特定的 CPU 核心
  • --cpu-shares:相对权重,多个容器竞争 CPU 时生效

IO 限制

# 限制读写速度
docker run -d \
--device-read-bps=/dev/sda:10mb \
--device-write-bps=/dev/sda:10mb \
nginx

# 限制读写 IOPS
docker run -d \
--device-read-iops=/dev/sda:1000 \
--device-write-iops=/dev/sda:1000 \
nginx

清理系统

# 清理未使用的容器、网络、镜像(悬空)
docker system prune

# 清理所有未使用的资源
docker system prune -a

# 包括数据卷
docker system prune -a --volumes

# 查看磁盘使用情况
docker system df

# 显示详细信息
docker system df -v

项目初始化(docker init)

docker init 是 Docker Desktop 提供的便捷命令,可以快速为项目生成 Docker 相关的配置文件。它能自动检测项目类型并创建合理的默认配置。

什么是 docker init?

手动编写 Dockerfile 和 compose.yaml 文件可能繁琐且容易出错。docker init 通过交互式向导,引导你完成以下文件的创建:

  • .dockerignore - 排除不需要复制到镜像的文件
  • Dockerfile - 构建镜像的脚本
  • compose.yaml - 多容器编排配置
  • README.Docker.md - Docker 使用说明文档

支持的项目类型

模板适用场景
GoGo 服务器应用
Java使用 Maven 的 Java 应用
NodeNode.js 服务器应用
PHP with ApachePHP Web 应用
PythonPython 服务器应用
RustRust 服务器应用
ASP.NET Core.NET Core 应用
Other通用起始模板

使用示例

基本用法

# 在项目目录中运行
docker init

# 交互式选择项目类型
? What application platform does your project use? [Use arrows to move]
> Go
Java
Node
PHP with Apache
Python
Rust
ASP.NET Core
Other

Go 项目示例

$ docker init
? What application platform does your project use? Go
? What version of Go do you want to use? 1.21
? What's the relative directory of your main package? .
? What port does your server listen on? 8080

CREATED: .dockerignore
CREATED: Dockerfile
CREATED: compose.yaml
CREATED: README.Docker.md

✔ Your Docker files are ready!
Take a moment to review them and tailor them to your application.
When you're ready, start your application by running: docker compose up --build

Node.js 项目示例

$ docker init
? What application platform does your project use? Node
? What version of Node do you want to use? 18
? Which package manager do you want to use? npm
? Do you want to run "npm run build" before starting your server? Yes
? What directory is your build output? dist
? What command do you want to use to start the app? npm start
? What port does your server listen on? 3000

CREATED: .dockerignore
CREATED: Dockerfile
CREATED: compose.yaml
CREATED: README.Docker.md

Python 项目示例

$ docker init
? What application platform does your project use? Python
? What version of Python do you want to use? 3.11
? What port do you want your app to listen on? 8000
? What is the command to run your app? python app.py

CREATED: .dockerignore
CREATED: Dockerfile
CREATED: compose.yaml
CREATED: README.Docker.md

生成的文件说明

运行 docker init 后,生成的文件需要根据实际项目进行调整。以下是一些常见注意事项:

Dockerfile

  • 检查基础镜像版本是否符合需求
  • 确认端口暴露是否正确
  • 验证启动命令是否准确
  • 根据需要添加额外的依赖安装

compose.yaml

  • 调整服务配置(环境变量、卷挂载等)
  • 添加依赖服务(数据库、缓存等)
  • 配置网络和卷

.dockerignore

  • 确认是否排除了所有不需要的文件
  • 添加项目特定的排除规则

注意事项

  • 如果目标文件已存在,docker init 会提示是否覆盖
  • 覆盖操作不可恢复,建议先备份重要文件
  • 生成的文件是起点模板,需要根据项目实际情况调整
  • 该命令需要 Docker Desktop 环境

上下文管理(docker context)

Docker Context 允许你在多个 Docker 环境之间切换,比如本地 Docker、远程服务器、云平台或 Swarm 集群。这对于管理多环境部署非常有用。

什么是 Context?

Context 是一组连接配置,定义了如何连接到 Docker daemon。每个 Context 包含:

配置项说明
EndpointDocker daemon 的连接地址
TLS 配置安全连接所需的证书
元数据Context 的描述信息

默认情况下,Docker 使用名为 default 的 Context,连接到本地 Docker daemon。

查看和管理 Context

列出所有 Context

# 列出所有 context
docker context ls

# 输出示例
NAME DESCRIPTION DOCKER ENDPOINT ERROR
default * Current DOCKER_HOST based configuration unix:///var/run/docker.sock
my-remote Remote Docker server ssh://[email protected]
swarm-cluster Swarm cluster tcp://swarm-manager:2376

查看当前使用的 Context

# 显示当前 context 名称
docker context show
# 输出:default

查看 Context 详情

# 查看详细信息
docker context inspect default

# 以 JSON 格式输出
docker context inspect --format json default

创建 Context

通过 SSH 连接远程 Docker

# 创建连接到远程服务器的 context
docker context create my-remote \
--docker "host=ssh://[email protected]"

# 指定 SSH 密钥
docker context create my-remote \
--docker "host=ssh://[email protected]" \
--description "Production server"

通过 TCP 连接

# 创建 TCP 连接的 context(需要 TLS)
docker context create my-tcp \
--docker "host=tcp://192.168.1.100:2376" \
--docker "ca=/path/to/ca.pem" \
--docker "cert=/path/to/cert.pem" \
--docker "key=/path/to/key.pem"

连接到 Swarm 集群

# 创建 Swarm context
docker context create swarm-cluster \
--docker "host=tcp://swarm-manager:2376" \
--description "Production Swarm cluster"

切换 Context

# 切换到指定 context
docker context use my-remote

# 验证当前 context
docker context show
# 输出:my-remote

# 后续命令将在该 context 上执行
docker ps
docker info

更新和删除 Context

# 更新 context 配置
docker context update my-remote \
--description "Updated description"

# 删除 context(不能删除当前使用的 context)
docker context rm my-remote

# 强制删除
docker context rm -f my-remote

导入导出 Context

# 导出 context 到文件
docker context export my-remote -o my-remote.dockercontext

# 从文件导入
docker context import my-remote-import my-remote.dockercontext

使用环境变量切换

除了使用 docker context use,还可以通过环境变量切换:

# 方式 1:使用 DOCKER_CONTEXT 环境变量
export DOCKER_CONTEXT=my-remote
docker ps # 在 my-remote context 上执行

# 方式 2:使用 DOCKER_HOST 环境变量(直接指定连接地址)
export DOCKER_HOST=ssh://[email protected]
docker ps

# 单次命令指定 context
DOCKER_CONTEXT=my-remote docker ps

优先级-H 参数 > DOCKER_HOST 环境变量 > DOCKER_CONTEXT 环境变量 > 当前 context

Context 使用场景

场景说明
开发与生产切换在本地开发和生产环境之间快速切换
多集群管理管理多个 Kubernetes 或 Swarm 集群
远程调试连接到远程服务器进行调试
CI/CD 流水线在不同环境间部署应用

实际示例

# 开发环境(本地)
docker context use default
docker compose up -d

# 切换到测试环境
docker context use test-server
docker compose up -d

# 切换到生产环境
docker context use production
docker service ls

Context 配置文件

Context 配置存储在 Docker 配置目录中:

  • Linux/macOS: ~/.docker/contexts/
  • Windows: C:\Users\<username>\.docker\contexts\

每个 context 有独立的目录,包含配置文件和证书。

Docker Desktop 命令行

Docker Desktop 提供了一组命令行工具,可以直接管理 Docker Desktop 应用程序本身。

常用命令

# 启动 Docker Desktop
docker desktop start

# 停止 Docker Desktop
docker desktop stop

# 重启 Docker Desktop
docker desktop restart

# 查看 Docker Desktop 状态
docker desktop status

# 打开 Docker Desktop 设置
docker desktop settings

# 打开 Docker Desktop Dashboard
docker dashboard

# 更新 Docker Desktop
docker desktop update

# 查看版本信息
docker desktop version

# 诊断问题
docker desktop diagnose

# 查看日志
docker desktop logs

使用场景

快速重启

# 当 Docker Desktop 出现问题时快速重启
docker desktop restart

故障诊断

# 运行诊断工具
docker desktop diagnose

# 查看日志定位问题
docker desktop logs --tail 100

后台启动

# 在 CI/CD 脚本中后台启动
docker desktop start --wait
# --wait 参数会等待 Docker 完全启动后再返回

CLI 配置文件

Docker CLI 的配置存储在配置目录中:

配置文件位置

  • Linux/macOS: ~/.docker/config.json
  • Windows: C:\Users\<username>\.docker\config.json

常用配置项

{
"auths": {
"https://index.docker.io/v1/": {
"auth": "base64-encoded-credentials"
}
},
"credsStore": "desktop",
"currentContext": "default",
"plugins": {
"compose": {
"enabled": true
}
},
"proxies": {
"default": {
"httpProxy": "http://proxy.example.com:8080",
"httpsProxy": "http://proxy.example.com:8080",
"noProxy": "localhost,127.0.0.1"
}
}
}

配置项说明

配置项说明
auths镜像仓库认证信息
credsStore凭据存储后端
currentContext当前使用的 context
pluginsCLI 插件配置
proxies代理配置

命令速查

镜像命令

命令说明
docker pull拉取镜像
docker images列出镜像
docker rmi删除镜像
docker tag创建标签
docker save导出镜像
docker load导入镜像
docker build构建镜像
docker history查看镜像历史
docker inspect查看镜像详情

容器命令

命令说明
docker run创建并运行容器
docker start启动容器
docker stop停止容器
docker restart重启容器
docker rm删除容器
docker ps列出容器
docker logs查看日志
docker exec执行命令
docker cp复制文件
docker stats资源统计
docker top查看进程
docker port查看端口

小结

Docker 基础命令的使用要点:

  • 命令结构docker [选项] 命令 [参数],分为镜像、容器、网络、数据卷等子命令
  • 镜像操作docker pull 拉取、docker images 列出、docker rmi 删除、docker save/load 导出导入
  • 容器操作docker run 创建运行、docker start/stop/restart 生命周期管理、docker exec 进入容器、docker logs 查看日志
  • 资源限制--memory 内存限制、--cpus CPU 限制、--device-read-bps IO 限制
  • 系统清理docker system prune 清理未使用资源、docker system df 查看磁盘使用

练习

  1. 拉取 nginx 镜像并运行一个容器
  2. 使用端口映射访问 nginx 服务
  3. 进入容器修改默认页面
  4. 查看容器日志和资源使用情况
  5. 清理所有停止的容器和悬空镜像

参考资源