Skip to main content

Container API Reference

Complete API reference for container management in Nekzus. These endpoints enable lifecycle management, monitoring, log streaming, and configuration export for containers across Docker and Kubernetes runtimes.


Overview

Nekzus provides a unified container management API that abstracts differences between Docker and Kubernetes runtimes. The API supports:

  • Lifecycle operations: Start, stop, and restart containers
  • Monitoring: Real-time resource statistics (CPU, memory, network)
  • Log streaming: WebSocket-based live log tailing
  • Bulk operations: Operate on multiple containers simultaneously
  • Configuration export: Export containers to Docker Compose format
Container Visibility

By default, the container list only includes containers that are linked to approved routes in Nekzus. This ensures you only see containers that are actively managed by the gateway.

Runtime Support

Nekzus supports multiple container runtimes through a unified abstraction layer.

RuntimeDescriptionContainer ID Format
dockerDocker containers12-character hex ID (e.g., abc123def456)
kubernetesKubernetes podsPod name (e.g., my-app-7d8f9b6c5d-x2k4m)

Use the runtime query parameter to target a specific runtime. If omitted, the primary configured runtime is used.


Authentication

Container endpoints support both IP-based and JWT authentication.

SourceAuthentication
Local networkNo authentication required
ExternalJWT token with write:* scope for mutations

Rate Limiting

Container endpoints share a rate limit pool:

CategoryRate LimitBurst
Container operations30 req/min20

List Containers

GET /api/v1/containers

Lists all containers from configured runtimes that are linked to approved routes.

Authentication: IP-based (local) or JWT

ParameterTypeDescription
runtimequeryFilter by runtime: docker or kubernetes
namespacequeryKubernetes namespace filter
curl https://localhost:8443/api/v1/containers

Response Fields

FieldTypeDescription
idstringContainer ID (12-character short form)
namestringContainer name
imagestringContainer image with tag
statestringContainer state (see states below)
statusstringHuman-readable status string
creatednumberCreation timestamp (Unix)
portsarrayPort mappings
labelsobjectContainer labels
runtimestringRuntime type (docker or kubernetes)
namespacestringKubernetes namespace (empty for Docker)

Container States

StateDescription
runningContainer is running
stoppedContainer is stopped
pausedContainer is paused (Docker)
restartingContainer is restarting
pendingPod is pending (Kubernetes)
failedPod has failed (Kubernetes)
createdContainer is created but not started
exitedContainer has exited

Inspect Container

GET /api/v1/containers/{containerId}

Returns detailed information about a specific container.

Authentication: IP-based (local) or JWT

curl https://localhost:8443/api/v1/containers/abc123def456
Runtime-Specific Response

For Docker containers, the response returns the raw Docker API format for backward compatibility. For Kubernetes pods, a normalized ContainerDetails format is returned.


Container Lifecycle

Container lifecycle operations are asynchronous. They return 202 Accepted immediately and send completion notifications via WebSocket.

POST /api/v1/containers/{containerId}/start

Starts a stopped container.

Authentication: IP-based (local) or JWT with write:* scope

curl -X POST https://localhost:8443/api/v1/containers/abc123def456/start

WebSocket Notification (Success):

{
"type": "container.start.completed",
"data": {
"containerId": "abc123def456",
"status": "started",
"message": "Container started successfully",
"timestamp": 1701388801
}
}

WebSocket Notification (Failure):

{
"type": "container.start.failed",
"data": {
"containerId": "abc123def456",
"error": "CONTAINER_START_FAILED",
"message": "Failed to start container",
"timestamp": 1701388801
}
}

POST /api/v1/containers/{containerId}/stop

Stops a running container with an optional grace period.

Authentication: IP-based (local) or JWT with write:* scope

ParameterTypeDefaultDescription
timeoutquery10Grace period in seconds (1-300)
curl -X POST "https://localhost:8443/api/v1/containers/abc123def456/stop?timeout=30"
Timeout Validation

The timeout must be between 1 and 300 seconds. Values outside this range return a 400 Bad Request error with code INVALID_TIMEOUT.

WebSocket Notification:

{
"type": "container.stop.completed",
"data": {
"containerId": "abc123def456",
"status": "stopped",
"message": "Container stopped successfully",
"timestamp": 1701388810
}
}
Health Status Update

When a container is stopped, the associated app is immediately marked as unhealthy. This triggers a health_change WebSocket notification to all connected devices.

POST /api/v1/containers/{containerId}/restart

Restarts a container with an optional grace period for the stop phase.

Authentication: IP-based (local) or JWT with write:* scope

ParameterTypeDefaultDescription
timeoutquery10Grace period in seconds (1-300)
curl -X POST https://localhost:8443/api/v1/containers/abc123def456/restart

WebSocket Notification:

{
"type": "container.restart.completed",
"data": {
"containerId": "abc123def456",
"status": "restarted",
"message": "Container restarted successfully",
"timestamp": 1701388815
}
}

Container Statistics

GET /api/v1/containers/{containerId}/stats

Returns real-time resource usage statistics for a container.

Authentication: IP-based (local) or JWT

curl https://localhost:8443/api/v1/containers/abc123def456/stats

Response Fields

FieldTypeDescription
containerIdstringContainer ID
cpu.usagenumberCPU usage percentage (0-100 per core)
cpu.coresUsednumberNumber of CPU cores being used
cpu.totalCoresnumberTotal available CPU cores
memory.usagenumberMemory usage percentage (0-100)
memory.usednumberMemory used in bytes
memory.limitnumberMemory limit in bytes
memory.availablenumberAvailable memory in bytes
network.rxnumberTotal bytes received
network.txnumberTotal bytes transmitted
timestampnumberStats collection timestamp (Unix)

GET /api/v1/containers/stats

Returns resource statistics for all running containers.

Authentication: IP-based (local) or JWT

curl https://localhost:8443/api/v1/containers/stats
Filtered Results

Only containers linked to approved apps are included in batch stats. Stopped containers are excluded.


Bulk Operations

Bulk operations execute on multiple containers concurrently with a maximum of 5 concurrent operations.

POST /api/v1/containers/start-all

Starts all stopped containers.

Authentication: IP-based (local) or JWT with write:* scope

curl -X POST https://localhost:8443/api/v1/containers/start-all

POST /api/v1/containers/stop-all

Stops all running containers.

Authentication: IP-based (local) or JWT with write:* scope

curl -X POST https://localhost:8443/api/v1/containers/stop-all

POST /api/v1/containers/restart-all

Restarts all containers.

Authentication: IP-based (local) or JWT with write:* scope

curl -X POST https://localhost:8443/api/v1/containers/restart-all

POST /api/v1/containers/batch

Performs an operation on a specific set of containers.

Authentication: IP-based (local) or JWT with write:* scope

FieldTypeRequiredDescription
actionstringYesOperation: start, stop, or restart
containerIdsarrayYesList of container IDs
timeoutnumberNoGrace period in seconds (for stop/restart)
curl -X POST https://localhost:8443/api/v1/containers/batch \
-H "Content-Type: application/json" \
-d '{
"action": "restart",
"containerIds": ["abc123def456", "def789abc123"],
"timeout": 15
}'

Error Responses

Error CodeHTTP StatusDescription
INVALID_ACTION400Action must be start, stop, or restart
EMPTY_CONTAINER_LIST400At least one container ID is required
NO_RUNTIME500No container runtime configured
CONTAINER_LIST_FAILED500Failed to list containers

Container Logs

Container logs are streamed via WebSocket for real-time updates.

WebSocket Log Streaming

To subscribe to container logs, send a message over an authenticated WebSocket connection.

Subscribe to Logs

{
"type": "container.logs.subscribe",
"data": {
"containerId": "abc123def456",
"tail": 100,
"follow": true,
"timestamps": true
}
}
FieldTypeDefaultDescription
containerIdstringRequiredContainer ID
tailnumber100Number of lines from end (max 1000)
followbooleantrueStream new logs in real-time
timestampsbooleanfalseInclude timestamps in output

Log Stream Messages

Stream Started:

{
"type": "container.logs.started",
"data": {
"containerId": "abc123def456",
"timestamp": 1701388800
}
}

Log Data:

{
"type": "container.logs",
"data": {
"containerId": "abc123def456",
"stream": "stdout",
"message": "2025-01-15T10:30:00Z INFO Starting application...",
"timestamp": 1701388800
}
}
FieldDescription
streamOutput stream: stdout or stderr
messageLog line content

Stream Ended:

{
"type": "container.logs.ended",
"data": {
"containerId": "abc123def456",
"reason": "stopped",
"timestamp": 1701388900
}
}
ReasonDescription
stoppedClient unsubscribed or disconnected
container_stoppedContainer stopped running
errorError occurred during streaming

Stream Error:

{
"type": "container.logs.error",
"data": {
"containerId": "abc123def456",
"error": "CONTAINER_NOT_FOUND",
"message": "Container not found",
"timestamp": 1701388800
}
}

Unsubscribe from Logs

{
"type": "container.logs.unsubscribe",
"data": {
"containerId": "abc123def456"
}
}
Memory Optimization

Log streaming uses buffer pooling (32KB buffers) to reduce garbage collection pressure during high-volume streaming. Frames larger than 1MB are skipped to prevent memory abuse.


Export Configuration

Export container configurations to Docker Compose format for migration or backup.

POST /api/v1/containers/{containerId}/export

Exports a single container configuration to Docker Compose format.

Authentication: IP-based (local) or JWT

FieldTypeDefaultDescription
sanitize_secretsbooleantrueReplace secret values with placeholders
include_volumesbooleantrueInclude volume definitions
include_networksbooleantrueInclude network definitions
curl -X POST https://localhost:8443/api/v1/containers/abc123def456/export \
-H "Content-Type: application/json" \
-d '{
"sanitize_secrets": true,
"include_volumes": true,
"include_networks": true
}'

POST /api/v1/containers/{containerId}/export/preview

Generates a preview of the export without triggering download.

Authentication: IP-based (local) or JWT

The request and response format is identical to the export endpoint.

POST /api/v1/containers/batch/export

Exports multiple containers to a single Docker Compose stack.

Authentication: IP-based (local) or JWT

ParameterTypeDescription
formatqueryOutput format: json (default) or zip
FieldTypeRequiredDescription
container_idsarrayYesList of container IDs to export
stack_namestringNoStack name (default: exported-stack)
sanitize_secretsbooleanNoReplace secrets with placeholders (default: true)
include_volumesbooleanNoInclude volumes (default: true)
include_networksbooleanNoInclude networks (default: true)
curl -X POST https://localhost:8443/api/v1/containers/batch/export \
-H "Content-Type: application/json" \
-d '{
"container_ids": ["abc123def456", "def789abc123"],
"stack_name": "my-stack"
}'
Partial Success

If some containers fail to inspect, the export continues with available containers and returns 206 Partial Content with warnings.

POST /api/v1/containers/batch/export/preview

Generates a preview of the batch export.

The request format is identical to the batch export endpoint.


Error Codes

CodeHTTP StatusDescription
CONTAINER_NOT_FOUND404Container does not exist
CONTAINER_START_FAILED500Failed to start container
CONTAINER_STOP_FAILED500Failed to stop container
CONTAINER_RESTART_FAILED500Failed to restart container
CONTAINER_ALREADY_STARTED409Container is already running
CONTAINER_ALREADY_STOPPED409Container is already stopped
CONTAINER_INSPECT_FAILED500Failed to inspect container
CONTAINER_STATS_FAILED500Failed to get container stats
CONTAINER_LIST_FAILED500Failed to list containers
INVALID_CONTAINER_ID400Container ID is required
INVALID_RUNTIME400Invalid runtime specified
INVALID_TIMEOUT400Timeout must be between 1 and 300 seconds
NO_RUNTIME500No container runtime configured
RUNTIME_UNAVAILABLE503Container runtime not available
EXPORT_FAILED500Failed to export container configuration
BATCH_EXPORT_FAILED500Failed to batch export containers
ALL_CONTAINERS_FAILED404Failed to inspect any containers

Kubernetes Path Format

For Kubernetes pods, an alternative path format is supported:

/api/v1/containers/{namespace}/{pod}/{action}
curl -X POST https://localhost:8443/api/v1/containers/default/my-app-7d8f9b6c5d-x2k4m/start

When using this path format, the runtime defaults to kubernetes automatically.


WebSocket Message Types Summary

Message TypeDirectionDescription
container.logs.subscribeClient -> ServerSubscribe to log streaming
container.logs.unsubscribeClient -> ServerUnsubscribe from log streaming
container.logs.startedServer -> ClientLog stream started
container.logsServer -> ClientLog data
container.logs.endedServer -> ClientLog stream ended
container.logs.errorServer -> ClientLog stream error
container.start.completedServer -> ClientContainer started
container.start.failedServer -> ClientContainer start failed
container.stop.completedServer -> ClientContainer stopped
container.stop.failedServer -> ClientContainer stop failed
container.restart.completedServer -> ClientContainer restarted
container.restart.failedServer -> ClientContainer restart failed