A Portainer API accessibility library for Node.js, written in TypeScript. This library provides a convenient wrapper around the Portainer API, allowing you to easily interact with your Portainer instance to manage environments, stacks, and containers.
- Authentication: Easy authentication using Portainer API tokens
- Environment Management: Fetch and manage Portainer environments (endpoints)
- Stack Management: Create, retrieve, start, stop, update, and delete stacks
- Container Management: Full container lifecycle management (start, stop, restart, remove, etc.)
- Factory Pattern: High-level factory methods for easy stack and container creation
- TypeScript Support: Fully typed interfaces for better development experience
- Logging: Built-in logging with debug package integration
npm install writetainer-libCreate a .env file in your project root with the following variables:
PORTAINER_URL=https://your-portainer-instance.com
PORTAINER_API_KEY=your-api-token-hereimport { PortainerApi, PortainerFactory, logInfo } from 'writetainer-lib';
// Get the singleton instance of PortainerApi
const api = PortainerApi.getInstance();
// Check connection status
const isConnected = await api.getStatus();
logInfo('Connected:', isConnected);
// Get all stacks
const stacks = await api.getStacks();
logInfo('Stacks:', stacks);
// Get all containers
const containers = await api.getContainers(true);
logInfo('Containers:', containers);import { PortainerFactory } from 'writetainer-lib';
const factory = PortainerFactory.getInstance();
const stackConfig = {
Name: "my-app-stack",
ComposeFile: `
services:
web:
image: nginx:latest
ports:
- "80:80"
restart: unless-stopped
`,
Env: [
{ name: "ENVIRONMENT", value: "production" }
]
};
// Create the stack
const stack = await factory.createStack(stackConfig);import { PortainerApi } from 'writetainer-lib';
const api = PortainerApi.getInstance();
// Start a container
await api.handleContainer({
action: 'start',
containerId: 'container-id-here',
environmentId: 1
});
// Stop a container
await api.handleContainer({
action: 'stop',
containerId: 'container-id-here'
});
// Remove a container with options
await api.handleContainer({
action: 'remove',
containerId: 'container-id-here',
options: {
force: true,
removeVolumes: true
}
});
// Restart a container with custom timeout
await api.handleContainer({
action: 'restart',
containerId: 'container-id-here',
options: {
timeout: 30000 // 30 seconds
}
});import { PortainerApi } from 'writetainer-lib';
const api = PortainerApi.getInstance();
// Start a stack
await api.startStack(stackId, environmentId);
// Stop a stack
await api.stopStack(stackId, environmentId);
// Update a stack with new compose content
await api.updateStack(stackId, newComposeContent, environmentId, true);
// Redeploy a stack (stop, pull, start)
await api.redeployStack(stackId, environmentId);
// Delete a stack
await api.deleteStack(stackId, environmentId);import { PortainerApi, getFirstEnvironmentId } from 'writetainer-lib';
const api = PortainerApi.getInstance();
// Get all environments
const environments = await api.getEnvironments();
// Get details of a specific environment
const envDetails = await api.getEnvironmentDetails(environmentId);
// Get first environment ID
const firstEnvId = await getFirstEnvironmentId();import { PortainerApi } from 'writetainer-lib';
const api = PortainerApi.getInstance();
// Get all containers (including stopped ones)
const allContainers = await api.getContainers(true);
// Get running containers only
const runningContainers = await api.getContainers(false);
// Get container details
const containerDetails = await api.getContainerDetails('container-id');
// Get container stats
const stats = await api.getContainerStats('container-id');
// Get images
const images = await api.getImages(environmentId);import {
getStackByName,
getStackById,
getContainerByDetails,
verifyStackCreation,
verifyContainerCreation
} from 'writetainer-lib';
// Find a stack by name
const stack = await getStackByName('my-stack-name');
// Find a stack by ID
const stack = await getStackById(123, environmentId);
// Find container by image or label
const container = await getContainerByDetails({
image: 'nginx:latest'
});
// Verify stack creation
const isVerified = await verifyStackCreation('my-stack', 5000, 3);
// Verify container creation
const isRunning = await verifyContainerCreation('my-container', 5000);Singleton class that provides access to all Portainer API operations.
Methods:
getInstance(environmentId?: number | null)- Get singleton instancegetEnvironments()- Fetch all environmentsgetEnvironmentDetails(environmentId)- Get environment detailsgetStacks()- Get all stacksgetContainers(includeAll, environmentId?)- Get containersgetContainerDetails(identifier, environmentId?)- Get container detailsgetContainerStats(identifier, environmentId?)- Get container statsgetImages(environmentId?)- Get imagesgetStatus(environmentId?)- Get system statushandleContainer(controls)- Execute container actionsstartStack(stackId, environmentId?)- Start a stackstopStack(stackId, environmentId?)- Stop a stackupdateStack(stackId, composeContent, environmentId?, pullImage?)- Update a stackredeployStack(stackId, environmentId?)- Redeploy a stackdeleteStack(stackId, environmentId?)- Delete a stackcleanupExistingContainer(containerName, environmentId?)- Cleanup a containerensureEnvId()- Ensure environment ID is set
Singleton factory class for creating resources with validation.
Methods:
getInstance(environmentId?: number | null)- Get singleton instancecreateStack(stackData, maxRetryCount?, timeoutMs?)- Create a new stackcreateContainer(containerData, maxRetryCount?, timeoutMs?)- Create a new container
Singleton class for authentication management.
Properties:
axiosInstance- Configured axios instanceisValidated- Authentication validation statusPortainerUrl- Portainer URL
Methods:
getInstance()- Get singleton instance
interface PortainerEnvironment {
Id: number;
Name: string;
}
interface PortainerStack {
Id: number;
Name: string;
EndpointId: number;
}
interface PortainerContainer {
Id: string;
Names: string[];
Image: string;
Labels: { [key: string]: string };
State: string;
Status: string;
// ... additional properties
}
interface PortainerImage {
Id: string;
RepoTags: string[];
Created: number;
Size: number;
}
interface PortainerStackContent {
Name: string;
ComposeFile: string | any;
Env?: Array<{ name: string; value: string }>;
FromAppTemplate?: boolean;
}The library uses the debug package for logging. To enable logs:
# Enable all logs
DEBUG=portainer-api:* node your-app.js
# Enable only info logs
DEBUG=portainer-api:info node your-app.js
# Enable error and warning logs
DEBUG=portainer-api:error,portainer-api:warn node your-app.jsYou can also use the built-in logging functions:
import { logInfo, logWarn, logError } from 'writetainer-lib';
logInfo('This is an info message');
logWarn('This is a warning');
logError('This is an error', errorObject);const stacks = await client.getStacks();
console.log(stacks);Fetch all containers (running and stopped) for the default environment.
const containers = await client.getContainers(true);
console.log(containers);const isConnected = await client.testConnection();
if (isConnected) {
console.log('Connected to Portainer!');
}new PortainerApiClient(portainerUrl: string, apiToken: string, environmentId?: number | null)
-
getEnvironments(): Promise<PortainerEnvironment[]>- Fetches a list of all Portainer environments.
-
getEnvironment(environmentId: number): Promise<PortainerEnvironment>- Fetches details of a specific environment.
-
getStacks(): Promise<PortainerStack[]>- Fetches a list of all stacks.
-
getContainers(includeAll: boolean): Promise<PortainerContainer[] | undefined>- Fetches a list of containers for the current environment.
includeAll: Set totrueto include stopped containers.
-
testConnection(): Promise<boolean>- Tests the connection to the Portainer API.
-
DefaultEnvironmentId(Getter/Setter)- Get or set the default environment ID used for container operations.
MIT