跳转到内容

Docker 常用命令

🧑‍💻 作者: crag
📦 版本: 0.0.1
📄 字数(字): 0
⏳ 时长(min): 0
📅 发表于: 2026-01-27
⏱️ 更新于: 2026-02-26

🔍 信息查看与帮助

  • 查看所有Docker命令的帮助
shell
docker --help
  • 查看特定命令的详细用法,例如查看 docker run 的帮助
shell
docker run --help

📦 镜像管理

  • 从Docker Hub搜索镜像,例如搜索nginx
shell
docker search nginx
  • 下载镜像(不指定标签默认为latest),例如下载最新版nginx
shell
docker pull nginx

# 指定标签
docker pull nginx:alpine
  • 列出本地已下载的镜像
shell
docker images

# 新语法
docker image ls
  • 删除指定的本地镜像(可以使用镜像ID或名称)
shell
docker rmi <image_id_or_name>
  • 根据Dockerfile构建自定义镜像(-t参数用于指定镜像标签)
shell
docker build -t my-image:tag /path/to/Dockerfile

🚀 容器生命周期管理

  • 创建并启动一个新容器
shell
# -d: 后台运行
# --name: 为容器命名
# -p: 端口映射(宿主机端口:容器端口)
# -v: 挂载数据卷(宿主机路径:容器路径)
docker run -d --name my-container -p 8080:80 -v /host/data:/container/data nginx
  • 启动、停止、重启已存在的容器
shell
# 启动
docker start my-container
shell
# 停止
docker stop my-container
shell
# 重启
docker restart my-container
  • 暂停/恢复容器中的所有进程
shell
# 暂停
docker pause my-container
shell
# 恢复
docker unpause my-container
  • 删除容器(删除已停止的容器,使用-f参数可强制删除运行中的容器)
shell
docker rm my-container

📊 容器操作与信息查看

  • 查看正在运行的容器
shell
docker ps
  • 查看所有容器(包括已停止的)
shell
docker ps -a
  • 查看容器的日志输出(-f 参数可以实时追踪日志)
shell
docker logs my-container

# 追踪日志
docker logs -f my-container
  • 在正在运行的容器内执行命令(常用/bin/bash进入交互式Shell)
shell
docker exec -it my-container /bin/bash
  • 在容器内执行单条命令
shell
docker exec my-container ls /app
  • 查看容器或镜像的底层详细信息(配置、网络、卷等)
shell
docker inspect my-container
  • 在容器和宿主机之间复制文件
shell
# 从容器复制文件到主机
docker cp my-container:/path/to/file /host/path/

# 从主机复制文件到容器
docker cp /host/path/file my-container:/container/path/

💾 数据卷管理

  • 列出所有Docker数据卷
shell
docker volume ls
  • 创建一个数据卷
shell
docker volume create my-volume
  • 查看数据卷的详细信息(包括存储路径)
shell
docker volume inspect my-volume
  • 删除指定的数据卷
shell
docker volume rm my-volume
  • 删除所有未被使用的数据卷
shell
docker volume prune

🌐 网络管理

  • 列出所有Docker网络
shell
docker network ls
  • 创建一个自定义网络(便于容器间通信)
shell
docker network create my-network
  • 查看网络的详细信息(包括连接的容器)
shell
docker network inspect my-network
  • 将容器连接到指定网络或从网络断开
shell
# 连接
docker network connect my-network my-container

# 断开
docker network disconnect my-network my-container

🎯 Docker Compose 项目管理

  • 在后台创建并启动所有服务(根据docker-compose.yml文件)
shell
docker compose up -d
  • 停止并移除所有服务相关的容器、网络等
shell
docker compose down
  • 列出当前工程中所有服务的容器状态
shell
docker compose ps
  • 查看一个或多个服务的日志输出
shell
docker compose logs
docker compose logs service-name
  • 启动、停止、重启所有服务
shell
# 启动
docker compose start

# 停止
docker compose stop

# 重启
docker compose restart
  • 在指定服务运行的容器内执行命令
shell
docker compose exec service-name /bin/bash

由一可爱小白兔支持