feat: 本地镜像支持批量启动运行(建容器并启动)
This commit is contained in:
1 parent
fbc8a5cb38
commit
c69864f1e3
4 files changed
+140
-1
No files matched your search
@@ -1,5 +1,14 @@
|
||||
# 更新日志
|
||||
|
||||
## 2026-10-27 → ✨ 本地镜像支持批量「启动运行」
|
||||
|
||||
- ✨ 本地镜像批量条新增「启动运行 N 个」:勾选镜像 → 弹窗设置重启策略 / 网络 / 端口映射 / 环境变量 → 一次为每个镜像创建并启动容器
|
||||
- ✨ 容器名 = 镜像名 + 4 位随机后缀,避免撞名;启动后自动出现在「运行的容器」并按最新安装排序
|
||||
- ✨ 端口映射仅在选中 1 个镜像时可用(批量会抢端口,已置灰并说明);支持 `8080:80` 与 `8080:80/udp`,逗号分隔多个
|
||||
- ✨ 无 CMD/ENTRYPOINT 的镜像自动用保活命令(`sh -c while true; sleep`),避免启动即退出;连 `sh` 都没有的空镜像给出明确提示并回滚容器
|
||||
- 🔧 新增 `POST /api/images/batch-run`(单批 20 个),网络下拉复用现有 bridge 网络列表
|
||||
- ✅ 实测:接口启动 alpine → 容器 `alpine-2gbw Up`;UI 勾选 1 个镜像 → 弹窗 42 个网络可选 → 启动成功 toast「已启动 1 个容器」;空镜像返回「镜像里没有可用的命令/外壳…无法自动保活」且不残留容器
|
||||
|
||||
## 2026-10-26 → ✨ 支持设置应用/容器性能上限(CPU 核数 + 内存)
|
||||
|
||||
- ✨ 容器抽屉与**应用详情页**新增「性能限制」:填 CPU 核数、内存 MB → 应用,用 Docker cgroup 硬限制,超过即被限流/限内存
|
||||
|
||||
+51
-1
@@ -1034,7 +1034,8 @@ async function renderImages() {
|
||||
<label class="bsel"><input type="checkbox" id="imgSelAll"> 全选</label>
|
||||
<span class="muted">已选 <b id="imgSelCount">${[...state.imgSel].filter(id => imgs.some(i => i.id === id)).length}</b> / ${imgs.length}</span>
|
||||
<span class="muted">批量导出会打包成一个 tar.gz</span>
|
||||
<button class="btn primary" id="imgExportSel" disabled>导出选中</button>
|
||||
<button class="btn primary" id="imgRunSel" disabled>启动运行</button>
|
||||
<button class="btn" id="imgExportSel" disabled>导出选中</button>
|
||||
<button class="btn danger" id="imgDelSel" disabled>删除选中</button>
|
||||
<button class="btn ghost" id="imgImport">导入镜像</button>
|
||||
<input type="file" id="imgFile" accept=".tar,.gz,.tgz,.tar.gz" style="display:none" />
|
||||
@@ -1060,6 +1061,7 @@ async function renderImages() {
|
||||
const n = $('#imgSelCount'); if (n) n.textContent = state.imgSel.size;
|
||||
const b = $('#imgExportSel'); if (b) { b.disabled = state.imgSel.size === 0; b.textContent = state.imgSel.size ? `导出选中 ${state.imgSel.size} 个` : '导出选中'; }
|
||||
const d = $('#imgDelSel'); if (d) { d.disabled = state.imgSel.size === 0; d.textContent = state.imgSel.size ? `删除选中 ${state.imgSel.size} 个` : '删除选中'; }
|
||||
const r1 = $('#imgRunSel'); if (r1) { r1.disabled = state.imgSel.size === 0; r1.textContent = state.imgSel.size ? `启动运行 ${state.imgSel.size} 个` : '启动运行'; }
|
||||
const a = $('#imgSelAll'); if (a) a.checked = state.imgSel.size > 0 && state.imgSel.size === idsAll.length;
|
||||
};
|
||||
$$('#view .imgsel').forEach(cb => {
|
||||
@@ -1101,6 +1103,54 @@ async function renderImages() {
|
||||
xhr.onerror = () => { btn.disabled = false; btn.textContent = '导入镜像'; toast('导入失败(网络错误)', true); };
|
||||
xhr.send(f);
|
||||
};
|
||||
const runBtn = $('#imgRunSel');
|
||||
if (runBtn) runBtn.onclick = async () => {
|
||||
const list = [...state.imgSel];
|
||||
if (!list.length) return;
|
||||
let nets = [{ name: 'bridge', label: 'bridge(默认)' }];
|
||||
try {
|
||||
const ns = await api('/api/networks');
|
||||
nets = ns.filter(n => n.driver === 'bridge').map(n => ({ name: n.name, label: n.name }));
|
||||
} catch (e) {}
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'modal-mask';
|
||||
overlay.innerHTML = `<div class="modal-card">
|
||||
<div class="modal-head"><b>从 ${list.length} 个镜像启动容器</b><span class="modal-x" id="mClose">✕</span></div>
|
||||
<div class="modal-body">
|
||||
<label class="m-row">重启策略 <select id="mRestart">
|
||||
<option value="unless-stopped">unless-stopped(推荐)</option>
|
||||
<option value="always">always</option>
|
||||
<option value="no">no</option>
|
||||
</select></label>
|
||||
<label class="m-row">网络 <select id="mNet">${nets.map(n => `<option value="${esc(n.name)}">${esc(n.label)}</option>`).join('')}</select></label>
|
||||
<label class="m-row">端口映射 <input id="mPorts" placeholder="8080:80" ${list.length > 1 ? 'disabled' : ''} />
|
||||
<span class="muted">${list.length > 1 ? '批量启动不支持端口,避免抢端口' : '可填多个,逗号分隔'}</span></label>
|
||||
<label class="m-row col">环境变量 <textarea id="mEnv" placeholder="TZ=Asia/Shanghai OTHER=1"></textarea></label>
|
||||
<div class="muted" style="font-size:11.5px;margin-top:6px">容器名 = 镜像名 + 随机后缀;无 CMD/ENTRYPOINT 的镜像会自动用保活命令,避免启动即退出。</div>
|
||||
</div>
|
||||
<div class="modal-foot"><button class="btn ghost" id="mCancel">取消</button><button class="btn primary" id="mGo">启动</button></div>
|
||||
</div>`;
|
||||
document.body.appendChild(overlay);
|
||||
const close = () => overlay.remove();
|
||||
overlay.querySelector('#mClose').onclick = close;
|
||||
overlay.querySelector('#mCancel').onclick = close;
|
||||
overlay.onclick = (e) => { if (e.target === overlay) close(); };
|
||||
overlay.querySelector('#mGo').onclick = async () => {
|
||||
const go = overlay.querySelector('#mGo');
|
||||
go.disabled = true; go.textContent = '启动中…';
|
||||
try {
|
||||
const r = await api('/api/images/batch-run', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: list, opts: { restart: overlay.querySelector('#mRestart').value, network: overlay.querySelector('#mNet').value, ports: overlay.querySelector('#mPorts').value, env: overlay.querySelector('#mEnv').value } }),
|
||||
});
|
||||
const fail = r.results.filter(x => !x.ok);
|
||||
toast(fail.length ? `已启动 ${r.started} 个,失败 ${fail.length} 个(${fail[0].error})` : `已启动 ${r.started} 个容器`);
|
||||
close();
|
||||
state.imgSel.clear();
|
||||
setTimeout(render, 800);
|
||||
} catch (e) { toast(e.message, true); go.disabled = false; go.textContent = '启动'; }
|
||||
};
|
||||
};
|
||||
const bd = $('#imgDelSel');
|
||||
if (bd) bd.onclick = async () => {
|
||||
const list = [...state.imgSel];
|
||||
|
||||
@@ -389,3 +389,16 @@ table.tb th.num{text-align:right}
|
||||
.lim-row input{width:92px;height:28px;padding:0 8px;border:1px solid #dfe6ef;border-radius:7px;font-size:12.5px}
|
||||
.lim-row input:focus{outline:none;border-color:#1a73e8;box-shadow:0 0 0 3px rgba(26,115,232,.10)}
|
||||
.lim-chip{display:inline-block;margin-left:6px;padding:1px 6px;border-radius:999px;background:#fff1f0;border:1px solid #ffd6d2;color:#c0392b;font-size:10.5px;font-weight:600;vertical-align:middle}
|
||||
|
||||
/* 通用弹窗 */
|
||||
.modal-mask{position:fixed;inset:0;background:rgba(18,24,34,.42);display:flex;align-items:center;justify-content:center;z-index:9998}
|
||||
.modal-card{background:#fff;border-radius:14px;width:min(460px,92vw);box-shadow:0 18px 48px rgba(0,0,0,.22);overflow:hidden}
|
||||
.modal-head{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid #eef2f7;font-size:14px}
|
||||
.modal-x{cursor:pointer;color:#93a0b4;font-size:13px}
|
||||
.modal-x:hover{color:#26303f}
|
||||
.modal-body{padding:14px 16px;display:flex;flex-direction:column;gap:10px}
|
||||
.m-row{display:flex;align-items:center;gap:8px;font-size:12.5px;color:#5a6b82}
|
||||
.m-row.col{flex-direction:column;align-items:stretch;gap:6px}
|
||||
.m-row select,.m-row input{height:30px;padding:0 9px;border:1px solid #dfe6ef;border-radius:8px;font-size:12.5px;flex:1}
|
||||
.m-row textarea{min-height:74px;padding:8px;border:1px solid #dfe6ef;border-radius:8px;font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px;resize:vertical}
|
||||
.modal-foot{display:flex;justify-content:flex-end;gap:8px;padding:12px 16px;border-top:1px solid #eef2f7;background:#fbfdff}
|
||||
@@ -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