اجرای کانتینر جدید
کانتینری جدید را ایجاد و فوراً اجرا میکند (ترکیبی از createContainer و startContainer).
🧩 دستور کلی
async runContainer(options)
شرح عملکرد
این متد کانتینری جدید را در یک مرحله ایجاد و اجرا میکند. شامل:
- تأیید گزینههای ورودی
- بررسی عدم موجودی کانتینر قبلی
- pull/register تصویر (اگر موجود نباشد)
- ایجاد bundle و filesystem
- تنظیم شبکه و veth pair
- ایجاد کانتینر
- شروع کانتینر
- ذخیره state در دیتابیس
- ارسال webhook
مهم: این متد ترکیبی است که هم createContainer را انجام میدهد و هم startContainer را. تصویر اگر موجود نباشد، خودکار pull میشود.
ورودیها
| پارامتر | نوع | اجباری | توضیح |
|---|---|---|---|
options | Object | بله | تمام پارامترهای اجرا |
options.containerId | String | بله | شناسه یکتای کانتینر |
options.image | String | بله | نام تصویر (alpine, nginx) |
options.tag | String | خیر | تگ تصویر (پیشفرض: latest) |
options.hostname | String | خیر | نام میزبان کانتینر |
options.args | String | خیر | دستور شروع/آرگومانها |
options.env | Array | خیر | متغیرهای محیطی (KEY=VALUE) |
options.cpus | Number | خیر | تعداد CPU مجاز |
options.memory | String | خیر | محدودیت حافظه (512m, 1GB) |
options.diskLimit | Number | خیر | محدودیت دیسک (MB) |
options.mount | Array | خیر | mount points برای ذخیرهسازی |
options.volume | Array | خیر | حجمهای مربوط (volume:path) |
options.network | String | خیر | نام شبکه (پیشفرض: kb0) |
options.ip | String | خیر | IP ثابت برای کانتینر |
options.mac | String | خیر | آدرس MAC کانتینر |
options.publish | Array | خیر | نگاشت پورت (hostPort:containerPort) |
options.privileged | Boolean | خیر | دسترسیهای ویژه (false) |
options.capAdd | Array | خیر | قابلیتهای اضافی |
options.capDrop | Array | خیر | قابلیتهای حذف شده |
options.restart | String | خیر | سیاست راهاندازی مجدد |
options.restartDelay | Number | خیر | تأخیر بین راهاندازیهای مجدد |
options.restartWindow | Number | خیر | پنجره زمانی برای سیاست |
options.maxAttempts | Number | خیر | حداکثر تعداد راهاندازی مجدد |
options.noNewKeyring | Boolean | خیر | حفظ session keyring |
options.noPivot | Boolean | خیر | عدم استفاده از pivot_root |
options.noShared | Boolean | خیر | CPU جداگانه (false) |
options.debug | Boolean | خیر | فعال کردن حالت debug |
خروجی
نوع: String (خروجی فرآیند اجرا)
نمونه خروجی:
Container started successfully
Running container: my-container (PID: 29429)
استثناها (Errors)
OptionConflict (422)
پیام: "Failed to validate create options." یا "Container already exists."
زمان رخ دادن: گزینههای نامعتبر یا کانتینر قبلاً وجود دارد
جزئیات:
{
"type": "VALIDATION_ERROR",
"statusCode": 422,
"error": "Invalid schema or container already exists"
}
راهنمای حل:
- تمام پارامترهای ضروری را بررسی کنید
- containerId را منحصرالفرد انتخاب کنید
- فرمتهای پارامتر را تأیید کنید
ResolveContainerName (500)
پیام: "Database error occurred while resolving container name or ID."
زمان رخ دادن: خطای دیتابیس در بررسی وجود کانتینر
جزئیات:
{
"type": "DB_ERROR",
"statusCode": 500,
"input": "container-id",
"error": "Database connection lost"
}
راهنمای حل:
- اتصال دیتابیس را بررسی کنید
- دیتابیس را راهاندازی کنید
GenericFailure (500)
پیام: "Generic failure during image pull or processing."
زمان رخ دادن: خطا در pull image، convertToBundle، یا سایر عملیات
جزئیات:
{
"type": "GENERIC_ERROR",
"statusCode": 500,
"error": "Image pull failed or operation failed"
}
راهنمای حل:
- نام تصویر را بررسی کنید
- registry دسترسیپذیری بررسی کنید
- اینترنت را تأیید کنید
CreateVethFail (500)
پیام: "Failed to create veth pair or set container IP."
زمان رخ دادن: خطا در تنظیم شبکه
جزئیات:
{
"type": "NETWORK_ERROR",
"statusCode": 500,
"containerId": "my-container",
"error": "Veth pair creation failed"
}
راهنمای حل:
- شبکه مشخص شده را بررسی کنید
- IP را تأیید کنید (باید در subnet باشد)
- شبکه driver را بررسی کنید
CreateFailure (500)
پیام: "Failed to create container through ContainerManager."
زمان رخ دادن: خطا در ایجاد کانتینر توسط runtime
جزئیات:
{
"type": "CONTAINER_SERVICE_ERROR",
"statusCode": 500,
"containerId": "my-container",
"error": "Runtime error: exit code"
}
راهنمای حل:
- لاگهای runtime را بررسی کنید
- منابع سیستم را تأیید کنید
- آرگومانهای دستور را بررسی کنید
UpdateContainerStateFailure (500)
پیام: "Failed to update container state in database."
زمان رخ دادن: خطا در ذخیره اطلاعات کانتینر
جزئیات:
{
"type": "DB_ERROR",
"statusCode": 500,
"containerId": "my-container",
"pid": 29429,
"error": "Database write failed"
}
راهنمای حل:
- دیتابیس را بررسی کنید
- فضای دیسک را تأیید کنید
مثالهای استفاده
مثال 1: اجرای کانتینر ساده
const K3Core = require('k3-core');
(async () => {
const k3 = new K3Core();
try {
const result = await k3.containerCore.runContainer({
containerId: 'simple-app',
image: 'alpine',
tag: 'latest'
});
console.log('Container running successfully');
console.log(result);
} catch (error) {
console.log(error.createFullMessage());
}
})();
مثال 2: اجرای کانتینر با محدودیت منابع
(async () => {
const k3 = new K3Core();
try {
const result = await k3.containerCore.runContainer({
containerId: 'web-server',
image: 'nginx',
tag: 'latest',
memory: '512MB',
cpus: 2,
diskLimit: 1024
});
console.log('Web server running with resource limits');
} catch (error) {
console.log(error.createFullMessage());
}
})();
مثال 3: اجرای کانتینر با متغیرهای محیطی
(async () => {
const k3 = new K3Core();
try {
const result = await k3.containerCore.runContainer({
containerId: 'app-prod',
image: 'node',
tag: '18',
env: [
'NODE_ENV=production',
'DATABASE_URL=postgresql://localhost/mydb',
'API_PORT=3000'
],
args: 'npm start'
});
console.log('Node app running with environment variables');
} catch (error) {
console.log(error.createFullMessage());
}
})();
مثال 4: اجرای کانتینر با تنظیمات شبکه
(async () => {
const k3 = new K3Core();
try {
const result = await k3.containerCore.runContainer({
containerId: 'api-service',
image: 'nginx',
tag: 'latest',
network: 'kb0',
ip: '192.168.100.50',
publish: ['8080:80', '8443:443']
});
console.log('API service running with network config');
} catch (error) {
console.log(error.createFullMessage());
}
})();
مثال 5: اجرای کانتینر با حجمها
(async () => {
const k3 = new K3Core();
try {
const result = await k3.containerCore.runContainer({
containerId: 'database',
image: 'postgres',
tag: '15',
volume: [
'db-data:/var/lib/postgresql/data',
'db-backup:/backup'
],
env: ['POSTGRES_PASSWORD=securepass']
});
console.log('Database running with persistent volumes');
} catch (error) {
console.log(error.createFullMessage());
}
})();
مثال 6: اجرای کانتینر با سیاست راهاندازی مجدد
(async () => {
const k3 = new K3Core();
try {
const result = await k3.containerCore.runContainer({
containerId: 'worker',
image: 'python',
tag: '3.11',
args: 'python worker.py',
restart: 'on-failure',
restartDelay: 5,
maxAttempts: 10
});
console.log('Worker running with restart policy');
} catch (error) {
console.log(error.createFullMessage());
}
})();
مثال 7: اجرای کانتینر با دسترسیهای ویژه
(async () => {
const k3 = new K3Core();
try {
const result = await k3.containerCore.runContainer({
containerId: 'privileged-app',
image: 'alpine',
tag: 'latest',
privileged: true,
capAdd: ['NET_ADMIN', 'SYS_TIME'],
capDrop: ['NET_RAW']
});
console.log('Privileged container with custom capabilities running');
} catch (error) {
console.log(error.createFullMessage());
}
})();
مثال 8: اجرای کانتینر پیچیده (جامع)
(async () => {
const k3 = new K3Core();
try {
const result = await k3.containerCore.runContainer({
containerId: 'complete-app',
image: 'myapp',
tag: '1.0.0',
hostname: 'app-server',
memory: '1GB',
cpus: 4,
diskLimit: 5120,
env: [
'NODE_ENV=production',
'LOG_LEVEL=info'
],
args: 'npm start',
network: 'kb0',
ip: '192.168.100.100',
publish: ['8080:3000'],
volume: [
'app-data:/data',
'app-logs:/var/log/app'
],
capAdd: ['NET_BIND_SERVICE'],
restart: 'unless-stopped',
restartDelay: 10,
debug: true
});
console.log('Complete application running');
} catch (error) {
console.log(error.createFullMessage());
}
})();
الگوهای خطا و راهنمای حل
الگو 1: کانتینر قبلاً وجود دارد
خطا: OptionConflict (422)
راهنمای حل:
try {
await k3.containerCore.runContainer({
containerId: 'existing-container',
image: 'alpine',
tag: 'latest'
});
} catch (error) {
if (error.type === 'VALIDATION_ERROR' && error.message.includes('already exists')) {
console.log('Container already exists');
const result = await k3.containerCore.runContainer({
containerId: 'existing-container-v2',
image: 'alpine',
tag: 'latest'
});
} else {
console.log(error.createFullMessage());
}
}
الگو 2: تصویر یافت نشد
خطا: GenericFailure (500)
راهنمای حل:
try {
await k3.containerCore.runContainer({
containerId: 'app',
image: 'non-existent-image',
tag: 'latest'
});
} catch (error) {
if (error.message.includes('pull') || error.message.includes('Image')) {
console.log('Image not found in registry');
const result = await k3.containerCore.runContainer({
containerId: 'app',
image: 'alpine',
tag: 'latest'
});
} else {
console.log(error.createFullMessage());
}
}
الگو 3: خطای شبکه
خطا: CreateVethFail (500)
راهنمای حل:
try {
await k3.containerCore.runContainer({
containerId: 'networked-app',
image: 'alpine',
tag: 'latest',
network: 'nonexistent-network',
ip: '10.0.0.100'
});
} catch (error) {
if (error.type === 'NETWORK_ERROR') {
console.log('Network configuration error');
const result = await k3.containerCore.runContainer({
containerId: 'networked-app',
image: 'alpine',
tag: 'latest',
network: 'kb0'
});
} else {
console.log(error.createFullMessage());
}
}
الگو 4: اجرای ایمن (safe run)
راهنمای حل:
const safeRunContainer = async (options) => {
try {
const containers = await k3.containerCore.listContainers({ all: true });
if (containers.some(c => c.name === options.containerId)) {
throw new Error(`Container ${options.containerId} already exists`);
}
console.log(`Creating container: ${options.containerId}`);
console.log(`Image: ${options.image}:${options.tag || 'latest'}`);
if (options.network && options.network !== 'host' && options.network !== 'none') {
console.log(`Network: ${options.network}`);
if (options.ip) {
console.log(`IP: ${options.ip}`);
}
}
const result = await k3.containerCore.runContainer(options);
console.log('Container running successfully');
return result;
} catch (error) {
console.log('Failed to run container:', error.message);
throw error;
}
};
await safeRunContainer({
containerId: 'safe-app',
image: 'alpine',
tag: 'latest'
});
الگو 5: اجرای کانتینر و انتظار برای آمادگی
راهنمای حل:
const runContainerAndWait = async (options, waitTime = 3000) => {
try {
console.log('Starting container...');
const result = await k3.containerCore.runContainer(options);
console.log('Container started, waiting for initialization...');
await new Promise(resolve => setTimeout(resolve, waitTime));
// بررسی وضعیت
const inspect = await k3.containerCore.inspectContainer(options.containerId);
if (inspect.state?.running) {
console.log(`Container running (PID: ${inspect.state?.pid})`);
} else {
console.log('Container not running');
}
return result;
} catch (error) {
console.log('Failed to run container:', error.message);
throw error;
}
};
await runContainerAndWait({
containerId: 'app',
image: 'node',
tag: 'latest',
args: 'npm start'
});
نکات عملی
-
containerId:
- منحصرالفرد باید باشد
- از کاراکترهای معتبر استفاده کنید (alphanumeric، -)
-
Image و Tag:
- فرمت: imageName:tagName
- پیشفرض: latest
- اگر تصویر موجود نیست، خودکار pull میشود
-
منابع:
- memory: 512m, 1GB, 2048MB
- cpus: 1, 2, 4 (تعداد CPU)
- diskLimit: MB
-
متغیرهای محیطی:
- فرمت: KEY=VALUE
- Array of strings
-
شبکه:
- network پیشفرض: kb0
- IP باید در subnet شبکه باشد
- host یا none برای شبکه خاص
-
حجمها:
- فرمت: volumeName:containerPath
- حجمها دادههای دائمی نگهداری کند
-
Debug:
- خروجی تفصیلی نشان دهد
- برای troubleshooting مفید است
-
Image Pull:
- تصویر خودکار pull میشود اگر نباشد
- اینترنت برای pull لازم است
دنباله عملیات
- Validation input
- Check container doesn't exist
- Pull/register image if needed
- Find blobs & persist
- Generate container hash
- Process volumes
- Setup network (veth pair)
- Create bundle from image
- Build DTO (config object)
- Create veth pair
- Convert image to bundle
- Create container via manager
- Get container PID
- Attach volumes
- Persist container record
- Persist container state
- Send webhooks
- Return result
مرجع سریع
| وضعیت | کد | توضیح |
|---|---|---|
| موفق | 200 | کانتینر اجرا شد |
| گزینه نامعتبر | 422 | OptionConflict |
| موجود | 422 | Container exists |
| شبکه خطا | 500 | CreateVethFail |
| خطای runtime | 500 | CreateFailure |
| خطای دیتابیس | 500 | UpdateContainerStateFailure |
تفاوت runContainer و createContainer
| جنبه | runContainer | createContainer |
|---|---|---|
| نتیجه | کانتینر ایجاد + شروع | فقط کانتینر ایجاد |
| PID | بلافاصله فعال | بعد از startContainer |
| وضعیت | Running | Created |
| استفاده | deployment فوری | پیکربندی و شروع بعدی |
نسخه: 1.3
تاریخ آپدیت: 9 آذرماه ۱۴۰۴
تیم توسعه: K3 Development Team