直接调用 Docker API 获取容器运行时长最可靠轻量,通过 /containers/{id}/json 接口读取 Created 时间戳并与当前时间差值计算;推荐用 curl --unix-socket 或 Python requests + dateutil.parser 解析 ISO 8601 时间,支持批量处理。
直接调用 docker api 获取容器运行时长,比进容器装 psutil 或解析日志更可靠、更轻量,也更适合批量操作。核心思路是:通过 /containers/{id}/json 接口拿到容器的 created 时间戳,再与当前时间做差,即可算出已运行时长。
获取容器创建时间并计算运行时长
Docker 守护进程的 REST API 返回的 JSON 中,Created 字段是 ISO 8601 格式的时间字符串(如 "2026-06-15T09:23:41.123456789Z"),代表容器创建时刻。只要知道当前系统时间,就能准确推算出运行了多久。
- API 地址为
http://localhost/containers/{container_id}/json,需通过 Unix socket 或 TCP 访问(默认监听unix:///var/run/docker.sock) - 推荐使用
curl --unix-socket直接调用,无需额外开启 TCP 端口,更安全 - Python 中可用
requests+dateutil.parser解析时间,避免手动处理时区和纳秒精度
Python 脚本示例:批量提取所有容器运行时长
以下脚本一次性获取全部容器(无论状态)的创建时间,并输出格式化后的运行时长:
#!/usr/bin/env python3
import requests
import json
from datetime import datetime
from dateutil import parser
import sys
<p>SOCKET_PATH = "/var/run/docker.sock"</p><p>def get_container_list():
r = requests.get(f"<a href="https://www.php.cn/link/79c3489e2392afd26733d285dee3abd0">https://www.php.cn/link/79c3489e2392afd26733d285dee3abd0</a>",
unix_socket=SOCKET_PATH)
r.raise_for_status()
return r.json()</p><p>def get_container_info(cid):
r = requests.get(f"<a href="https://www.php.cn/link/f0547ecd4e64a31e247c34b64547f812">https://www.php.cn/link/f0547ecd4e64a31e247c34b64547f812</a>",
unix_socket=SOCKET_PATH)
r.raise_for_status()
return r.json()</p><p>def format_duration(seconds):
days, s = divmod(int(seconds), 86400)
hours, s = divmod(s, 3600)
mins, secs = divmod(s, 60)
if days > 0:
return f"{days}d {hours}h"
elif hours > 0:
return f"{hours}h {mins}m"
else:
return f"{mins}m {secs}s"</p><p>if <strong>name</strong> == "<strong>main</strong>":
containers = get_container_list()
now = datetime.now().astimezone()</p><pre class="brush:php;toolbar:false;">print(f"{'ID':12} {'NAME':20} {'STATUS':12} {'RUNTIME'}")
print("-" * 65)
for c in containers:
cid = c["Id"][:12]
name = c["Names"][0].lstrip("/")
status = c["Status"]
try:
info = get_container_info(cid)
created = parser.isoparse(info["Created"])
runtime = now - created
duration_str = format_duration(runtime.total_seconds())
except Exception as e:
duration_str = "N/A"
print(f"{cid:12} {name:20} {status:12} {duration_str}")
python-docx Skill功能概述python-docx Skill是一项面向实际任务的技能,主要用于本Skill提供使用python-docx生成专业Word文档的标准方法和最佳实践;生成安全服务方案文档;核心要点生成技术架构设计文档;生成任何需要专业排版的Word文档;核心库 : python-docx;使用与执行辅助库 : docx.shared , docx.enum , docx.oxml.ns;标准代码模板;1. 文档初始化;2. 字体设置(必须!它将相关步骤、工具调用和结果整理方式集
保存为 docker-runtime.py,确保当前用户有读取 /var/run/docker.sock 的权限(通常需加入 docker 用户组),然后运行:python3 docker-runtime.py
Shell 版本:轻量快速,适合 CI 或定时任务
如果不想依赖 Python,纯 Bash 也能完成关键逻辑(借助 jq 和 date):
#!/bin/bash
# 需安装 jq:apt install jq / brew install jq
SOCKET="/var/run/docker.sock"
<p>echo "ID NAME STATUS RUNTIME"
echo "-----------------------------------------------------------"</p><p>docker ps -aq --format '{{.ID}} {{.Names}} {{.Status}}' | while read cid name status; do
name=${name#/} # 去掉开头的 /
created=$(curl -s --unix-socket "$SOCKET" "<a href="https://www.php.cn/link/3e53ae683f8e8c84221db763b30fe907">https://www.php.cn/link/3e53ae683f8e8c84221db763b30fe907</a>" 2>/dev/null | jq -r '.Created' | cut -d'T' -f1)</p><p>if [[ -n "$created" && "$created" != "null" ]]; then</p><h1>粗略按天计算(跳过时分秒,避免 date 处理时区复杂性)</h1><pre class="brush:php;toolbar:false;">age_days=$(( ( $(date -d "$(date +%Y-%m-%d)" +%s) - $(date -d "$created" +%s) ) / 86400 ))
if [ $age_days -gt 0 ]; then
runtime="${age_days}d"
else
runtime="<p>else
runtime="N/A"
fi</p><p>printf "%-15s %-20s %-12s %s\n" "${cid:0:12}" "$name" "$status" "$runtime"
done
</p>注意事项与优化点
-
权限问题:脚本需能访问
/var/run/docker.sock。生产环境不建议直接赋权给普通用户,可考虑用 systemd socket 拦截或改用 Docker-in-Docker 方式隔离 -
性能考虑:批量查上百个容器时,逐个请求
/json接口会有延迟。如需极致性能,可先用docker ps -a --format获取 ID+状态+创建时间(部分版本支持{{.CreatedAt}}),再只对关键容器查详细信息 -
状态 vs 运行时长:已退出容器的
Created时间仍有效,但“运行时长”应理解为“自创建至今”,而非“持续运行时长”。若需精确的**持续运行时间**(即排除重启间隔),需结合State.StartedAt字段 -
健康检查补充:运行时长只是基础指标,搭配
State.Health.Status可判断是否长期卡在 unhealthy 状态,用于自动告警
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










