教程 docker tutorial

查看与管理容器(ps / top / logs)

Docker 提供多种命令用于查看和管理容器状态,帮助开发者监控运行情况、调试问题和维护服务。

1. 查看容器状态(docker ps)

bash
docker ps           # 查看正在运行的容器
docker ps -a        # 查看所有容器(包括已停止)
docker ps -l        # 查看最近创建的容器

`

常用参数:

  • --filter:按条件过滤容器,例如状态、名称
bash
docker ps --filter "status=running"
docker ps --filter "name=myapp"
  • --format:自定义输出格式
bash
docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Status}}"

2. 查看容器进程(docker top)

查看容器内正在运行的进程:

bash
docker top mycontainer

示例输出:

text
UID        PID   PPID  C STIME TTY          TIME CMD
root       1234  1     0 10:00 ?        00:00:00 /bin/bash
  • 用于检查容器内部进程状态和资源占用

3. 查看容器日志(docker logs)

获取容器输出日志:

bash
docker logs mycontainer
docker logs -f mycontainer   # 实时跟踪日志
docker logs --tail 100 mycontainer  # 查看最近 100 行日志
  • -f / --follow:跟踪输出日志
  • --since / --until:按时间筛选日志

4. 其他容器管理命令

  • 停止容器:
bash
docker stop mycontainer
  • 启动容器:
bash
docker start mycontainer
  • 重启容器:
bash
docker restart mycontainer
  • 删除容器:
bash
docker rm mycontainer

5. 实用技巧

  • 将 ps、top 和 logs 结合使用,可快速诊断容器状态和问题
  • 对长期运行的服务容器,使用日志文件或日志聚合工具(ELK/Prometheus)进行监控

掌握容器查看与管理命令,能够让你及时监控运行状态、发现问题并进行调试,提高容器运维效率。