npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

writetainer-lib

v26.3.2-0.3

Published

A TypeScript library for interacting with the Portainer API to manage Docker containers and stacks programmatically.

Downloads

21

Readme

Writetainer-Lib

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.

Features

  • 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

Installation

npm install writetainer-lib

Prerequisites

Create a .env file in your project root with the following variables:

PORTAINER_URL=https://your-portainer-instance.com
PORTAINER_API_KEY=your-api-token-here

Quick Start

Basic Usage

import { 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);

Creating Stacks with Factory

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);

Container Management

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
    }
});

Stack Operations

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);

Environment Management

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();

Resource Fetching

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);

Utility Functions

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);

API Reference

Main Classes

PortainerApi

Singleton class that provides access to all Portainer API operations.

Methods:

  • getInstance(environmentId?: number | null) - Get singleton instance
  • getEnvironments() - Fetch all environments
  • getEnvironmentDetails(environmentId) - Get environment details
  • getStacks() - Get all stacks
  • getContainers(includeAll, environmentId?) - Get containers
  • getContainerDetails(identifier, environmentId?) - Get container details
  • getContainerStats(identifier, environmentId?) - Get container stats
  • getImages(environmentId?) - Get images
  • getStatus(environmentId?) - Get system status
  • handleContainer(controls) - Execute container actions
  • startStack(stackId, environmentId?) - Start a stack
  • stopStack(stackId, environmentId?) - Stop a stack
  • updateStack(stackId, composeContent, environmentId?, pullImage?) - Update a stack
  • redeployStack(stackId, environmentId?) - Redeploy a stack
  • deleteStack(stackId, environmentId?) - Delete a stack
  • cleanupExistingContainer(containerName, environmentId?) - Cleanup a container
  • ensureEnvId() - Ensure environment ID is set

PortainerFactory

Singleton factory class for creating resources with validation.

Methods:

  • getInstance(environmentId?: number | null) - Get singleton instance
  • createStack(stackData, maxRetryCount?, timeoutMs?) - Create a new stack
  • createContainer(containerData, maxRetryCount?, timeoutMs?) - Create a new container

PortainerAuth

Singleton class for authentication management.

Properties:

  • axiosInstance - Configured axios instance
  • isValidated - Authentication validation status
  • PortainerUrl - Portainer URL

Methods:

  • getInstance() - Get singleton instance

Type Definitions

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;
}

Logging

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.js

You 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);

Get Stacks

const stacks = await client.getStacks();
console.log(stacks);

Get Containers

Fetch all containers (running and stopped) for the default environment.

const containers = await client.getContainers(true);
console.log(containers);

Test Connection

const isConnected = await client.testConnection();
if (isConnected) {
    console.log('Connected to Portainer!');
}

API Reference

PortainerApiClient

Constructor

new PortainerApiClient(portainerUrl: string, apiToken: string, environmentId?: number | null)

Methods

  • 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 to true to 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.

License

MIT