feat: 本地镜像显示使用状态,运行中镜像不可删除

This commit is contained in:
jinghui committed 2026-10-26 21:42:41 +08:00
1 parent f9701c92d8
commit f8ed288b5e
3 files changed
+73 -14

No files matched your search

+42 -7
View File
@@ -1024,17 +1024,52 @@ app.post('/api/containers', async (req, res) => {
/* ---------------- 接口:镜像 / 网络 ---------------- */
app.get('/api/images', async (req, res) => {
try {
const imgs = await docker.listImages({ all: false });
res.json(imgs.map(i => ({
id: i.Id, shortId: i.Id.replace('sha256:', '').slice(0, 12), tags: i.RepoTags || [],
size: i.Size, created: i.Created, containers: i.Containers || 0,
})).sort((a, b) => b.size - a.size));
const [imgs, conts] = await Promise.all([
docker.listImages({ all: false }),
docker.listContainers({ all: true }),
]);
const use = new Map();
for (const c of conts) {
const k = c.ImageID;
if (!use.has(k)) use.set(k, { running: [], stopped: [] });
const b = use.get(k);
(c.State === 'running' ? b.running : b.stopped).push(strip((c.Names || [])[0]));
}
const list = imgs.map(i => {
const u = use.get(i.Id) || { running: [], stopped: [] };
return {
id: i.Id, shortId: i.Id.replace('sha256:', '').slice(0, 12), tags: i.RepoTags || [],
size: i.Size, created: i.Created, containers: i.Containers || 0,
running: u.running, stopped: u.stopped,
inUse: u.running.length > 0,
canDelete: u.running.length === 0 && u.stopped.length === 0,
};
}).sort((a, b) => b.size - a.size);
res.json({
items: list,
summary: {
total: list.length,
totalSize: list.reduce((a, b) => a + b.size, 0),
inUse: list.filter(i => i.inUse).length,
deletable: list.filter(i => i.canDelete).length,
deletableSize: list.filter(i => i.canDelete).reduce((a, b) => a + b.size, 0),
},
});
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.delete('/api/images/:id', async (req, res) => {
try { await docker.getImage(req.params.id).remove({ force: req.query.force === '1' }); res.json({ ok: true }); }
catch (e) { res.status(500).json({ error: e.message }); }
try {
const id = req.params.id;
const img = await docker.getImage(id).inspect();
const conts = await docker.listContainers({ all: true });
const running = conts.filter(c => c.ImageID === img.Id && c.State === 'running').map(c => strip((c.Names || [])[0]));
if (running.length) return res.status(409).json({ error: `该镜像正被运行中的容器使用(${running.slice(0, 3).join('、')}${running.length > 3 ? ' 等' : ''}),不能删除` });
const stopped = conts.filter(c => c.ImageID === img.Id).map(c => strip((c.Names || [])[0]));
if (stopped.length) return res.status(409).json({ error: `该镜像被已停止的容器引用(${stopped.slice(0, 3).join('、')}),请先删除容器` });
await docker.getImage(id).remove({ force: req.query.force === '1' });
res.json({ ok: true });
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.post('/api/images/prune', async (req, res) => {