feat:容器的增删改查,多个容器创建
This commit is contained in:
parent
b56b4b05bf
commit
877ab8e850
@ -1,7 +1,17 @@
|
|||||||
import type { NextConfig } from "next";
|
import type { NextConfig } from "next";
|
||||||
|
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
/* config options here */
|
/* config options here */
|
||||||
|
webpack(config, { isServer }) {
|
||||||
|
// 仅在服务器端处理 .node 文件
|
||||||
|
if (isServer) {
|
||||||
|
config.module.rules.push({
|
||||||
|
test: /\.node$/,
|
||||||
|
use: 'node-loader', // 使用 node-loader 处理 .node 文件
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return config;
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export default nextConfig;
|
export default nextConfig;
|
||||||
|
@ -10,6 +10,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"bun": "^1.1.42",
|
"bun": "^1.1.42",
|
||||||
|
"cpu-features": "^0.0.10",
|
||||||
"dockerode": "^4.0.2",
|
"dockerode": "^4.0.2",
|
||||||
"next": "15.1.3",
|
"next": "15.1.3",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
|
@ -1,67 +1,100 @@
|
|||||||
// app/actions/containerActions.ts
|
'use server'
|
||||||
|
|
||||||
import Docker from 'dockerode';
|
import Docker from 'dockerode';
|
||||||
|
|
||||||
|
// 只在服务器端执行的操作
|
||||||
const docker = new Docker({ socketPath: '/var/run/docker.sock' });
|
const docker = new Docker({ socketPath: '/var/run/docker.sock' });
|
||||||
|
|
||||||
// 批量创建容器
|
|
||||||
export async function createContainers(count: number, baseName: string, startingPorts: [number, number]) {
|
export async function createContainers(count: number, baseName: string, startingPorts: [number, number]) {
|
||||||
const [vncStart, sshStart] = startingPorts;
|
const [vncStart, sshStart] = startingPorts;
|
||||||
const promises = [];
|
const promises = [];
|
||||||
|
|
||||||
|
// 只在服务器端加载 cpu-features
|
||||||
|
if (typeof window === 'undefined') {
|
||||||
|
try {
|
||||||
|
const cpuFeatures = require('cpu-features'); // 仅在服务器端加载
|
||||||
|
console.log('CPU Features:', cpuFeatures); // 打印所有的 CPU 特性对象
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading cpu-features:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for (let i = 0; i < count; i++) {
|
for (let i = 0; i < count; i++) {
|
||||||
const containerName = `${baseName}-${i}`;
|
const containerName = `${baseName}-${i}`;
|
||||||
const vncPort = vncStart + i;
|
const vncPort = vncStart + i;
|
||||||
const sshPort = sshStart + i;
|
const sshPort = sshStart + i;
|
||||||
|
|
||||||
const container = docker.createContainer({
|
try {
|
||||||
Image: 'ubuntu-xfce-vnc-ssh', // 使用你的镜像
|
const container = await docker.createContainer({
|
||||||
name: containerName,
|
Image: 'dockerp.com/dcsunset/ubuntu-vnc:latest', // 使用你的镜像
|
||||||
ExposedPorts: {
|
name: containerName,
|
||||||
'5900/tcp': {}, // VNC 默认端口
|
ExposedPorts: {
|
||||||
'22/tcp': {}, // SSH/SFTP 默认端口
|
'5900/tcp': {}, // VNC 默认端口
|
||||||
},
|
'22/tcp': {}, // SSH/sSFTP 默认端口
|
||||||
HostConfig: {
|
|
||||||
PortBindings: {
|
|
||||||
'5900/tcp': [{ HostPort: vncPort.toString() }],
|
|
||||||
'22/tcp': [{ HostPort: sshPort.toString() }],
|
|
||||||
},
|
},
|
||||||
},
|
HostConfig: {
|
||||||
});
|
PortBindings: {
|
||||||
|
'5900/tcp': [{ HostPort: vncPort.toString() }],
|
||||||
|
'22/tcp': [{ HostPort: sshPort.toString() }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
promises.push(container);
|
promises.push(container);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error creating container:', error);
|
||||||
|
throw new Error(`Failed to create container ${containerName}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return Promise.all(promises);
|
return Promise.all(promises);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 关闭容器
|
// 其他容器操作如 stop、remove 等
|
||||||
export async function stopContainer(containerName: string) {
|
export async function stopContainer(containerName: string) {
|
||||||
const container = docker.getContainer(containerName);
|
try {
|
||||||
await container.stop();
|
const container = docker.getContainer(containerName);
|
||||||
return { message: `Container ${containerName} stopped successfully.` };
|
await container.stop();
|
||||||
|
return { message: `Container ${containerName} stopped successfully.` };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error stopping container:', error);
|
||||||
|
throw new Error(`Failed to stop container ${containerName}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 删除容器
|
|
||||||
export async function removeContainer(containerName: string) {
|
export async function removeContainer(containerName: string) {
|
||||||
const container = docker.getContainer(containerName);
|
try {
|
||||||
await container.remove();
|
const container = docker.getContainer(containerName);
|
||||||
return { message: `Container ${containerName} removed successfully.` };
|
await container.remove();
|
||||||
|
return { message: `Container ${containerName} removed successfully.` };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error removing container:', error);
|
||||||
|
throw new Error(`Failed to remove container ${containerName}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取容器信息
|
|
||||||
export async function getContainerInfo(containerName: string) {
|
export async function getContainerInfo(containerName: string) {
|
||||||
const container = docker.getContainer(containerName);
|
try {
|
||||||
const info = await container.inspect();
|
const container = docker.getContainer(containerName);
|
||||||
return {
|
const info = await container.inspect();
|
||||||
containerName: info.Name,
|
return {
|
||||||
state: info.State.Status,
|
containerName: info.Name,
|
||||||
ports: info.NetworkSettings.Ports,
|
state: info.State.Status,
|
||||||
};
|
ports: info.NetworkSettings.Ports,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error retrieving container info:', error);
|
||||||
|
throw new Error(`Failed to retrieve info for container ${containerName}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 启动容器
|
|
||||||
export async function startContainer(containerName: string) {
|
export async function startContainer(containerName: string) {
|
||||||
const container = docker.getContainer(containerName);
|
try {
|
||||||
await container.start();
|
const container = docker.getContainer(containerName);
|
||||||
return { message: `Container ${containerName} started successfully.` };
|
await container.start();
|
||||||
|
return { message: `Container ${containerName} started successfully.` };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error starting container:', error);
|
||||||
|
throw new Error(`Failed to start container ${containerName}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
171
src/app/page.tsx
171
src/app/page.tsx
@ -1,101 +1,80 @@
|
|||||||
import Image from "next/image";
|
'use client'
|
||||||
|
|
||||||
|
import React, { useState } from 'react';
|
||||||
|
|
||||||
|
// 引入 Server Actions
|
||||||
|
import { createContainers, stopContainer, removeContainer, getContainerInfo, startContainer } from '@/actions/createContainers';
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
return (
|
const [error, setError] = useState<string | null>(null);
|
||||||
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
|
const [message, setMessage] = useState<string | null>(null);
|
||||||
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start">
|
|
||||||
<Image
|
|
||||||
className="dark:invert"
|
|
||||||
src="/next.svg"
|
|
||||||
alt="Next.js logo"
|
|
||||||
width={180}
|
|
||||||
height={38}
|
|
||||||
priority
|
|
||||||
/>
|
|
||||||
<ol className="list-inside list-decimal text-sm text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
|
|
||||||
<li className="mb-2">
|
|
||||||
Get started by editing{" "}
|
|
||||||
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-semibold">
|
|
||||||
src/app/page.tsx
|
|
||||||
</code>
|
|
||||||
.
|
|
||||||
</li>
|
|
||||||
<li>Save and see your changes instantly.</li>
|
|
||||||
</ol>
|
|
||||||
|
|
||||||
<div className="flex gap-4 items-center flex-col sm:flex-row">
|
// 创建容器的函数
|
||||||
<a
|
const handleCreateContainers = async () => {
|
||||||
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5"
|
try {
|
||||||
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
const count = 3; // 创建容器的数量
|
||||||
target="_blank"
|
const baseName = 'my-container'; // 容器名称前缀
|
||||||
rel="noopener noreferrer"
|
const startingPorts: [number, number] = [5901, 2201]; // VNC 和 SSH 起始端口
|
||||||
>
|
const containers = await createContainers(count, baseName, startingPorts);
|
||||||
<Image
|
setMessage(`Successfully created ${containers.length} containers.`);
|
||||||
className="dark:invert"
|
} catch (err: any) {
|
||||||
src="/vercel.svg"
|
setError(`Error creating containers: ${err.message}`);
|
||||||
alt="Vercel logomark"
|
}
|
||||||
width={20}
|
};
|
||||||
height={20}
|
|
||||||
/>
|
// 停止容器的函数
|
||||||
Deploy now
|
const handleStopContainer = async (containerName: string) => {
|
||||||
</a>
|
try {
|
||||||
<a
|
const result = await stopContainer(containerName);
|
||||||
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:min-w-44"
|
setMessage(result.message);
|
||||||
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
} catch (err: any) {
|
||||||
target="_blank"
|
setError(`Error stopping container: ${err.message}`);
|
||||||
rel="noopener noreferrer"
|
}
|
||||||
>
|
};
|
||||||
Read our docs
|
|
||||||
</a>
|
// 删除容器的函数
|
||||||
|
const handleRemoveContainer = async (containerName: string) => {
|
||||||
|
try {
|
||||||
|
const result = await removeContainer(containerName);
|
||||||
|
setMessage(result.message);
|
||||||
|
} catch (err: any) {
|
||||||
|
setError(`Error removing container: ${err.message}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 获取容器信息的函数
|
||||||
|
const handleGetContainerInfo = async (containerName: string) => {
|
||||||
|
try {
|
||||||
|
const info = await getContainerInfo(containerName);
|
||||||
|
setMessage(`Container: ${info.containerName}, State: ${info.state}, Ports: ${JSON.stringify(info.ports)}`);
|
||||||
|
} catch (err: any) {
|
||||||
|
setError(`Error getting container info: ${err.message}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 启动容器的函数
|
||||||
|
const handleStartContainer = async (containerName: string) => {
|
||||||
|
try {
|
||||||
|
const result = await startContainer(containerName);
|
||||||
|
setMessage(result.message);
|
||||||
|
} catch (err: any) {
|
||||||
|
setError(`Error starting container: ${err.message}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h1>Container Management</h1>
|
||||||
|
{error && <p style={{ color: 'red' }}>{error}</p>}
|
||||||
|
{message && <p style={{ color: 'green' }}>{message}</p>}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<button onClick={handleCreateContainers}>Create Containers</button>
|
||||||
|
<button onClick={() => handleStopContainer('my-container-0')}>Stop Container</button>
|
||||||
|
<button onClick={() => handleRemoveContainer('my-container-0')}>Remove Container</button>
|
||||||
|
<button onClick={() => handleGetContainerInfo('my-container-0')}>Get Container Info</button>
|
||||||
|
<button onClick={() => handleStartContainer('my-container-0')}>Start Container</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
);
|
||||||
<footer className="row-start-3 flex gap-6 flex-wrap items-center justify-center">
|
|
||||||
<a
|
|
||||||
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
|
|
||||||
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
>
|
|
||||||
<Image
|
|
||||||
aria-hidden
|
|
||||||
src="/file.svg"
|
|
||||||
alt="File icon"
|
|
||||||
width={16}
|
|
||||||
height={16}
|
|
||||||
/>
|
|
||||||
Learn
|
|
||||||
</a>
|
|
||||||
<a
|
|
||||||
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
|
|
||||||
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
>
|
|
||||||
<Image
|
|
||||||
aria-hidden
|
|
||||||
src="/window.svg"
|
|
||||||
alt="Window icon"
|
|
||||||
width={16}
|
|
||||||
height={16}
|
|
||||||
/>
|
|
||||||
Examples
|
|
||||||
</a>
|
|
||||||
<a
|
|
||||||
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
|
|
||||||
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
>
|
|
||||||
<Image
|
|
||||||
aria-hidden
|
|
||||||
src="/globe.svg"
|
|
||||||
alt="Globe icon"
|
|
||||||
width={16}
|
|
||||||
height={16}
|
|
||||||
/>
|
|
||||||
Go to nextjs.org →
|
|
||||||
</a>
|
|
||||||
</footer>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user