feat:容器的增删改查,多个容器创建
This commit is contained in:
parent
b56b4b05bf
commit
877ab8e850
@ -2,6 +2,16 @@ import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* 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;
|
||||
|
@ -10,6 +10,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"bun": "^1.1.42",
|
||||
"cpu-features": "^0.0.10",
|
||||
"dockerode": "^4.0.2",
|
||||
"next": "15.1.3",
|
||||
"react": "^19.0.0",
|
||||
|
@ -1,24 +1,36 @@
|
||||
// app/actions/containerActions.ts
|
||||
'use server'
|
||||
|
||||
import Docker from 'dockerode';
|
||||
|
||||
// 只在服务器端执行的操作
|
||||
const docker = new Docker({ socketPath: '/var/run/docker.sock' });
|
||||
|
||||
// 批量创建容器
|
||||
export async function createContainers(count: number, baseName: string, startingPorts: [number, number]) {
|
||||
const [vncStart, sshStart] = startingPorts;
|
||||
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++) {
|
||||
const containerName = `${baseName}-${i}`;
|
||||
const vncPort = vncStart + i;
|
||||
const sshPort = sshStart + i;
|
||||
|
||||
const container = docker.createContainer({
|
||||
Image: 'ubuntu-xfce-vnc-ssh', // 使用你的镜像
|
||||
try {
|
||||
const container = await docker.createContainer({
|
||||
Image: 'dockerp.com/dcsunset/ubuntu-vnc:latest', // 使用你的镜像
|
||||
name: containerName,
|
||||
ExposedPorts: {
|
||||
'5900/tcp': {}, // VNC 默认端口
|
||||
'22/tcp': {}, // SSH/SFTP 默认端口
|
||||
'22/tcp': {}, // SSH/sSFTP 默认端口
|
||||
},
|
||||
HostConfig: {
|
||||
PortBindings: {
|
||||
@ -29,27 +41,40 @@ export async function createContainers(count: number, baseName: string, starting
|
||||
});
|
||||
|
||||
promises.push(container);
|
||||
} catch (error) {
|
||||
console.error('Error creating container:', error);
|
||||
throw new Error(`Failed to create container ${containerName}`);
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.all(promises);
|
||||
}
|
||||
|
||||
// 关闭容器
|
||||
// 其他容器操作如 stop、remove 等
|
||||
export async function stopContainer(containerName: string) {
|
||||
try {
|
||||
const container = docker.getContainer(containerName);
|
||||
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) {
|
||||
try {
|
||||
const container = docker.getContainer(containerName);
|
||||
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) {
|
||||
try {
|
||||
const container = docker.getContainer(containerName);
|
||||
const info = await container.inspect();
|
||||
return {
|
||||
@ -57,11 +82,19 @@ export async function getContainerInfo(containerName: string) {
|
||||
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) {
|
||||
try {
|
||||
const container = docker.getContainer(containerName);
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
|
167
src/app/page.tsx
167
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() {
|
||||
return (
|
||||
<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)]">
|
||||
<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>
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
<div className="flex gap-4 items-center flex-col sm:flex-row">
|
||||
<a
|
||||
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"
|
||||
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/vercel.svg"
|
||||
alt="Vercel logomark"
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
Deploy now
|
||||
</a>
|
||||
<a
|
||||
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"
|
||||
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Read our docs
|
||||
</a>
|
||||
// 创建容器的函数
|
||||
const handleCreateContainers = async () => {
|
||||
try {
|
||||
const count = 3; // 创建容器的数量
|
||||
const baseName = 'my-container'; // 容器名称前缀
|
||||
const startingPorts: [number, number] = [5901, 2201]; // VNC 和 SSH 起始端口
|
||||
const containers = await createContainers(count, baseName, startingPorts);
|
||||
setMessage(`Successfully created ${containers.length} containers.`);
|
||||
} catch (err: any) {
|
||||
setError(`Error creating containers: ${err.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
// 停止容器的函数
|
||||
const handleStopContainer = async (containerName: string) => {
|
||||
try {
|
||||
const result = await stopContainer(containerName);
|
||||
setMessage(result.message);
|
||||
} catch (err: any) {
|
||||
setError(`Error stopping container: ${err.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
// 删除容器的函数
|
||||
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>
|
||||
</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