feat: 本地镜像支持批量启动运行(建容器并启动)
This commit is contained in:
1 parent
fbc8a5cb38
commit
c69864f1e3
4 files changed
+140
-1
No files matched your search
@@ -1140,6 +1140,73 @@ app.get('/api/images', async (req, res) => {
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.post('/api/images/batch-run', async (req, res) => {
|
||||
try {
|
||||
const ids = Array.isArray(req.body && req.body.ids) ? req.body.ids.filter(x => typeof x === 'string').slice(0, 20) : [];
|
||||
if (!ids.length) return res.status(400).json({ error: '未选择镜像' });
|
||||
const o = (req.body && req.body.opts) || {};
|
||||
const restart = ['no', 'unless-stopped', 'always', 'on-failure'].includes(o.restart) ? o.restart : 'unless-stopped';
|
||||
const network = String(o.network || 'bridge');
|
||||
const envObj = {};
|
||||
for (const line of String(o.env || '').split('\n')) {
|
||||
const m = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
|
||||
if (m) envObj[m[1]] = m[2];
|
||||
}
|
||||
const env = Object.entries(envObj).map(([k, v]) => `${k}=${v}`);
|
||||
|
||||
// 端口映射只在单镜像时支持,避免批量抢端口
|
||||
let exposed = {}, bindings = {};
|
||||
if (ids.length === 1 && o.ports) {
|
||||
for (const pair of String(o.ports).split(',').map(x => x.trim()).filter(Boolean)) {
|
||||
const m = pair.match(/^(\d{1,5}):(\d{1,5})(?:\/(tcp|udp))?$/);
|
||||
if (!m) return res.status(400).json({ error: `端口映射格式不对:${pair}(应为 8080:80)` });
|
||||
const key = `${m[2]}/${m[3] || 'tcp'}`;
|
||||
exposed[key] = {};
|
||||
(bindings[key] = bindings[key] || []).push({ HostPort: String(m[1]) });
|
||||
}
|
||||
}
|
||||
|
||||
const results = [];
|
||||
for (const id of ids) {
|
||||
let depName = '';
|
||||
try {
|
||||
const img = await docker.getImage(id).inspect();
|
||||
const tag = (img.RepoTags || [])[0] || img.Id.slice(7, 19);
|
||||
const base = tag.split('/').pop().split(':')[0].replace(/[^a-zA-Z0-9_.-]/g, '').slice(0, 24) || 'img';
|
||||
let name = `${base}-${Math.random().toString(36).slice(2, 6)}`;
|
||||
const cfg = {
|
||||
Image: img.Id,
|
||||
name,
|
||||
Env: env,
|
||||
Tty: true,
|
||||
OpenStdin: true,
|
||||
HostConfig: { RestartPolicy: { Name: restart }, NetworkMode: network, ...(Object.keys(bindings).length ? { PortBindings: bindings } : {}) },
|
||||
...(Object.keys(exposed).length ? { ExposedPorts: exposed } : {}),
|
||||
};
|
||||
// 有命令的镜像用默认 CMD;没有 CMD/ENTRYPOINT 的镜像给个保活命令,否则容器立刻退出
|
||||
const hasCmd = (img.Config && ((img.Config.Cmd && img.Config.Cmd.length) || (img.Config.Entrypoint && img.Config.Entrypoint.length)));
|
||||
if (!hasCmd) cfg.Cmd = ['sh', '-c', 'while true; do sleep 3600; done'];
|
||||
const c = await docker.createContainer(cfg);
|
||||
try {
|
||||
await c.start();
|
||||
} catch (e2) {
|
||||
try { await c.remove({ force: true }); } catch (_) {}
|
||||
const raw = String(e2.message || '');
|
||||
throw new Error(/executable file not found/i.test(raw) ? '镜像里没有可用的命令/外壳(如空镜像),无法自动保活,请手动指定启动命令' : raw);
|
||||
}
|
||||
depName = name;
|
||||
results.push({ id, tag, name, ok: true });
|
||||
} catch (e) {
|
||||
results.push({ id, tag: '', name: depName, ok: false, error: e.message.replace(/^\(HTTP code \d+\) unexpected - /, '') });
|
||||
}
|
||||
}
|
||||
const ok = results.filter(r => r.ok).length;
|
||||
inspectAll().catch(() => {});
|
||||
pushEvent('info', null, `从镜像批量启动 ${ok} 个容器`, `失败 ${results.length - ok} 个`);
|
||||
res.json({ ok: true, started: ok, results });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.post('/api/images/batch-delete', async (req, res) => {
|
||||
try {
|
||||
const ids = Array.isArray(req.body && req.body.ids) ? req.body.ids.filter(x => typeof x === 'string').slice(0, 100) : [];
|
||||
|
||||
Reference in new issue
Block a user