پرش به مطلب اصلی

ایجاد کانتینر

کانتینری جدید با تصویر، پیکربندی منابع و تنظیمات شبکه ایجاد می‌کند.


🧩 دستور کلی

async createContainer(options)

شرح عملکرد

این متد یک کانتینر جدید ایجاد می‌کند. شامل:

  • بارگذاری تصویر (pull از registry اگر نیاز باشد)
  • تنظیم منابع (CPU، حافظه، دیسک)
  • تنظیم شبکه (IP ثابت، پورت، MAC)
  • اتصال حجم‌ها
  • تنظیم سیاست راه‌اندازی مجدد
  • ایجاد bundle و فایل‌سیستم

مهم: فرآیند خط‌به‌خط و اگر در هر مرحله خطایی رخ دهد، عملیات متوقف می‌شود.


ورودی‌ها

پارامترنوعاجباریتوضیح
optionsObjectبلهتمام پارامترهای ایجاد
options.containerIdStringبلهشناسه یکتای کانتینر
options.imageStringبلهنام تصویر (alpine, nginx)
options.tagStringخیرتگ تصویر (پیش‌فرض: latest)
options.hostnameStringخیرنام میزبان کانتینر
options.argsStringخیردستور شروع/آرگومان‌ها
options.envArrayخیرمتغیرهای محیطی (KEY=VALUE)
options.cpusNumberخیرتعداد CPU مجاز
options.memoryStringخیرمحدودیت حافظه (512m, 1GB)
options.diskLimitNumberخیرمحدودیت دیسک (MB)
options.mountArrayخیرmount points برای ذخیره‌سازی
options.volumeArrayخیرحجم‌های مربوط (volume:path)
options.networkStringخیرنام شبکه (پیش‌فرض: kb0)
options.ipStringخیرIP ثابت برای کانتینر
options.macStringخیرآدرس MAC کانتینر
options.publishArrayخیرنگاشت پورت (hostPort:containerPort)
options.privilegedBooleanخیردسترسی‌های ویژه (false)
options.capAddArrayخیرقابلیت‌های اضافی
options.capDropArrayخیرقابلیت‌های حذف شده
options.restartStringخیرسیاست راه‌اندازی مجدد
options.restartDelayNumberخیرتأخیر بین راه‌اندازی‌های مجدد
options.restartWindowNumberخیرپنجره زمانی برای سیاست
options.maxAttemptsNumberخیرحداکثر تعداد راه‌اندازی مجدد
options.noNewKeyringBooleanخیرحفظ session keyring
options.noPivotBooleanخیرعدم استفاده از pivot_root
options.noSharedBooleanخیرCPU جداگانه (false)
options.debugBooleanخیرفعال کردن حالت debug

خروجی

نوع: String (خروجی فرآیند ایجاد)

نمونه خروجی:

Using debug verbosity
Loading container from config file: `/var/lib/k3/containers/5018594e25b3c2a5/config.json`
Using bundle: /var/lib/k3/overlays/5018594e25b3c2a5
Creating container: `105`
Creating exec fifo: /run/crun/105/exec.fifo
Running with prefork enabled
Reading config file: `/var/lib/k3/containers/5018594e25b3c2a5/config.json`
Writing config file to: `/run/crun/105/config.json`
Opening hooks output
Using cgroupfs cgroup manager
Using container host UID `0` and GID `0`
Running linux container
Unsharing namespace: `pid`
Unsharing namespace: `ipc`
Unsharing namespace: `uts`
Unsharing namespace: `mount`
Unsharing namespace: `user`
Unsharing namespace: `network`
Set rlimit: soft = `1024`, hard = `1024`
Running container PID after fork: `29429`
Running `create` hooks
Writing container status
finish

استثناها (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، findBlobs، یا getImageSize

جزئیات:

{
"type": "GENERIC_ERROR",
"statusCode": 500,
"error": "Image pull failed or blob not found"
}

راهنمای حل:

  • نام تصویر را بررسی کنید
  • 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 را بررسی کنید
  • منابع سیستم را تأیید کنید
  • آرگومان‌های دستور را بررسی کنید

PIDNotFound (404)

پیام: "No process found for the specified container."

زمان رخ دادن: PID پروسس کانتینر یافت نشود

جزئیات:

{
"type": "NOT_FOUND",
"statusCode": 404,
"containerId": "my-container",
"error": "PID not found"
}

راهنمای حل:

  • آرگومان‌های دستور کانتینر را بررسی کنید
  • دستور می‌تواند فوری اتمام یابد
  • لاگ‌های کانتینر را مطالعه کنید

UpdateContainerStateFailure (500)

پیام: "Failed to update container state in database."

زمان رخ دادن: خطا در ذخیره اطلاعات کانتینر

جزئیات:

{
"type": "DB_ERROR",
"statusCode": 500,
"containerId": "my-container",
"pid": 29429,
"error": "Database write failed"
}

راهنمای حل:

  • دیتابیس را بررسی کنید
  • فضای دیسک را تأیید کنید

سیاست‌های راه‌اندازی مجدد

سیاستتوضیح
noneراه‌اندازی مجدد نخواهد شد (پیش‌فرض)
alwaysهمیشه راه‌اندازی مجدد شود
unless-stoppedتا زمانی که متوقف نشده، راه‌اندازی مجدد شود
on-failureدر صورت خطا راه‌اندازی مجدد شود

مثال‌های استفاده

مثال 1: ایجاد کانتینر ساده

const K3Core = require('k3-core');

(async () => {
const k3 = new K3Core();

try {
const result = await k3.containerCore.createContainer({
containerId: 'simple-app',
image: 'alpine',
tag: 'latest'
});
console.log('Container created successfully');
console.log(result);
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 2: ایجاد کانتینر با محدودیت منابع

(async () => {
const k3 = new K3Core();

try {
const result = await k3.containerCore.createContainer({
containerId: 'web-server',
image: 'nginx',
tag: 'latest',
memory: '512MB',
cpus: 2,
diskLimit: 1024
});
console.log('Web server container created with resource limits');
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 3: ایجاد کانتینر با متغیرهای محیطی

(async () => {
const k3 = new K3Core();

try {
const result = await k3.containerCore.createContainer({
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 container created with environment variables');
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 4: ایجاد کانتینر با تنظیمات شبکه

(async () => {
const k3 = new K3Core();

try {
const result = await k3.containerCore.createContainer({
containerId: 'api-service',
image: 'nginx',
tag: 'latest',
network: 'kb0',
ip: '192.168.100.50',
mac: 'AA:BB:CC:DD:EE:FF',
publish: ['8080:80', '8443:443']
});
console.log('API service with network config created');
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 5: ایجاد کانتینر با حجم‌ها

(async () => {
const k3 = new K3Core();

try {
const result = await k3.containerCore.createContainer({
containerId: 'database',
image: 'postgres',
tag: '15',
volume: [
'db-data:/var/lib/postgresql/data',
'db-backup:/backup'
],
env: ['POSTGRES_PASSWORD=securepass']
});
console.log('Database container with persistent volumes created');
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 6: ایجاد کانتینر با سیاست راه‌اندازی مجدد

(async () => {
const k3 = new K3Core();

try {
const result = await k3.containerCore.createContainer({
containerId: 'worker',
image: 'python',
tag: '3.11',
args: 'python worker.py',
restart: 'on-failure',
restartDelay: 5,
maxAttempts: 10
});
console.log('Worker container with restart policy created');
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 7: ایجاد کانتینر با دسترسی‌های ویژه

(async () => {
const k3 = new K3Core();

try {
const result = await k3.containerCore.createContainer({
containerId: 'privileged-app',
image: 'alpine',
tag: 'latest',
privileged: true,
capAdd: ['NET_ADMIN', 'SYS_TIME'],
capDrop: ['NET_RAW']
});
console.log('Privileged container with custom capabilities created');
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 8: ایجاد کانتینر پیچیده (جامع)

(async () => {
const k3 = new K3Core();

try {
const result = await k3.containerCore.createContainer({
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 container created');
} catch (error) {
console.log(error.createFullMessage());
}
})();

الگوهای خطا و راهنمای حل

الگو 1: کانتینر قبلاً وجود دارد

خطا: OptionConflict (422)

راهنمای حل:

try {
await k3.containerCore.createContainer({
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.createContainer({
containerId: 'existing-container-v2',
image: 'alpine',
tag: 'latest'
});
} else {
console.log(error.createFullMessage());
}
}

الگو 2: تصویر یافت نشد

خطا: GenericFailure (500)

راهنمای حل:

try {
await k3.containerCore.createContainer({
containerId: 'app',
image: 'non-existent-image',
tag: 'latest'
});
} catch (error) {
if (error.message.includes('pull') || error.message.includes('copyImage')) {
console.log('Image not found in registry');
const result = await k3.containerCore.createContainer({
containerId: 'app',
image: 'alpine',
tag: 'latest'
});
} else {
console.log(error.createFullMessage());
}
}

الگو 3: خطای شبکه

خطا: CreateVethFail (500)

راهنمای حل:

try {
await k3.containerCore.createContainer({
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.createContainer({
containerId: 'networked-app',
image: 'alpine',
tag: 'latest',
network: 'kb0'
});
} else {
console.log(error.createFullMessage());
}
}

الگو 4: ایجاد محتاط با بررسی قبلی

راهنمای حل:

const safeCreateContainer = 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 with image: ${options.image}:${options.tag || 'latest'}`);

if (options.network && options.network !== 'host' && options.network !== 'none') {
console.log(`Using network: ${options.network}`);
}

const result = await k3.containerCore.createContainer(options);
console.log('Container created successfully');
return result;

} catch (error) {
console.log('Failed to create container:', error.message);
throw error;
}
};

await safeCreateContainer({
containerId: 'safe-app',
image: 'alpine',
tag: 'latest'
});

نکات عملی

  1. containerId:

    • منحصرالفرص باید باشد
    • از کاراکترهای معتبر استفاده کنید (alphanumeric، -)
  2. Image و Tag:

    • فرمت: imageName:tagName
    • پیش‌فرض: latest
    • اگر تصویر موجود نیست، pull می‌شود
  3. منابع:

    • memory: 512m, 1GB, 2048MB
    • cpus: 1, 2, 4 (تعداد CPU)
    • diskLimit: MB
  4. متغیرهای محیطی:

    • فرمت: KEY=VALUE
    • Array of strings
  5. شبکه:

    • network پیش‌فرض: kb0
    • IP باید در subnet شبکه باشد
    • host یا none برای شبکه خاص
  6. حجم‌ها:

    • فرمت: volumeName:containerPath
    • حجم‌ها داده‌های دائمی نگهداری کند
  7. Debug:

    • خروجی تفصیلی نشان دهد
    • برای troubleshooting مفید است

مراحل ایجاد

  1. Validation input
  2. Check container doesn't exist
  3. Pull/register image if needed
  4. Generate container hash
  5. Process volumes
  6. Setup network (veth pair)
  7. Create bundle from image
  8. Build DTO (config object)
  9. Create veth pair
  10. Create container via manager
  11. Get container PID
  12. Attach volumes
  13. Persist container record
  14. Persist container state
  15. Send webhooks

مرجع سریع

وضعیتکدتوضیح
موفق200کانتینر ایجاد شد
گزینه نامعتبر422OptionConflict
موجود422Container exists
شبکه خطا500CreateVethFail
خطای runtime500CreateFailure
خطای دیتابیس500UpdateContainerStateFailure

نسخه: 1.3
تاریخ آپدیت: 9 آذرماه ۱۴۰۴
تیم توسعه: K3 Development Team