teguh02/portainer-ce

PHP Library for Portainer Community Edition API - A comprehensive PHP client for managing Docker containers, Kubernetes clusters, and edge computing resources through Portainer CE API

v1.0.0 2025-09-07 15:01 UTC

This package is auto-updated.

Last update: 2025-09-07 15:11:44 UTC


README

Latest Version Total Downloads License

A comprehensive PHP library for managing Portainer Community Edition API. This library provides complete access to all Portainer CE features through an easy-to-use repository pattern.

Features

  • Authentication - Login with username/password or OAuth
  • Endpoints Management - Manage Docker and Kubernetes environments
  • Docker Resources - Access dashboard and images
  • Container Management - Start, stop, restart, pause, unpause, remove containers
  • Stack Deployment - Deploy Docker Compose stacks (WordPress, etc.)
  • Kubernetes Management - Manage namespaces, pods, services, ingresses, etc.
  • Edge Computing - Manage edge groups, jobs, and stacks
  • Custom Templates - Create and manage custom templates
  • Backup & Restore - System backup and restore functionality
  • User Management - Manage users and roles
  • Registry Management - Manage Docker registries
  • Settings - Configure Portainer settings

Installation

composer require teguh02/portainer-ce

Requirements

  • PHP 7.4 or higher
  • GuzzleHTTP 7.0 or higher
  • PHP JSON extension

Quick Start

Initialize Client

<?php

use Teguh02\PortainerCE\PortainerClient;

// Initialize client
$portainer = new PortainerClient('http://localhost:9000');

// Authenticate with username/password
$authResponse = $portainer->auth()->authenticate('admin', 'password');
echo "JWT Token: " . $authResponse['jwt'];

// Or set token manually
$portainer->setJwtToken('your-jwt-token-here');

Managing Endpoints

// List all endpoints
$endpoints = $portainer->endpoints()->list();

// Get endpoint by ID
$endpoint = $portainer->endpoints()->get(1);

// Create new endpoint
$newEndpoint = $portainer->endpoints()->create([
    'name' => 'My Docker Host',
    'URL' => 'tcp://docker-host:2376',
    'type' => 1, // Docker
    'publicURL' => 'docker-host.example.com'
]);

// Update endpoint
$portainer->endpoints()->update(1, [
    'name' => 'Updated Docker Host'
]);

// Delete endpoint
$portainer->endpoints()->delete(1);

Managing Docker Resources

// Get Docker dashboard
$dashboard = $portainer->docker()->getDashboard(1);

// Get Docker images
$images = $portainer->docker()->getImages(1, true); // true to show all images

// Get container GPUs
$gpus = $portainer->docker()->getContainerGpus(1, 'container-id');

Container Management

// List containers
$containers = $portainer->containers()->list(1, true); // true to show all containers

// Get container details
$container = $portainer->containers()->get(1, 'container-id');

// Create container
$newContainer = $portainer->containers()->create(1, [
    'name' => 'my-container',
    'image' => 'nginx:alpine',
    'ports' => ['80/tcp' => [['HostPort' => '8080']]]
]);

// Container control
$portainer->containers()->start(1, 'container-id');
$portainer->containers()->stop(1, 'container-id');
$portainer->containers()->restart(1, 'container-id');
$portainer->containers()->pause(1, 'container-id');
$portainer->containers()->unpause(1, 'container-id');

// Get container logs
$logs = $portainer->containers()->getLogs(1, 'container-id', true, true, 0, 0, true, false, 10);

// Get container stats
$stats = $portainer->containers()->getStats(1, 'container-id');

// Execute command in container
$result = $portainer->containers()->exec(1, 'container-id', [
    'command' => ['echo', 'Hello World']
]);

// Remove container
$portainer->containers()->remove(1, 'container-id', true, false);

Stack Deployment (Docker Compose)

// List stacks
$stacks = $portainer->stacks()->list();

// Deploy WordPress stack
$wordpressStack = $portainer->stacks()->createStandaloneFromString(1, [
    'name' => 'wordpress-site',
    'stackFileContent' => 'version: "3.8"
services:
  wordpress:
    image: wordpress:latest
    ports:
      - "8080:80"
    environment:
      WORDPRESS_DB_HOST: db:3306
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: password
      WORDPRESS_DB_NAME: wordpress
    depends_on:
      - db
  db:
    image: mysql:8.0
    environment:
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: password
      MYSQL_ROOT_PASSWORD: root_password'
]);

// Deploy stack from repository
$stackFromRepo = $portainer->stacks()->createStandaloneFromRepository(1, [
    'name' => 'stack-from-git',
    'repositoryURL' => 'https://github.com/user/repo.git',
    'composeFilePathInRepository' => 'docker-compose.yml'
]);

// Stack control
$portainer->stacks()->start(1, 1); // stack ID, endpoint ID
$portainer->stacks()->stop(1, 1);
$portainer->stacks()->update(1, ['stackFileContent' => $newCompose]);

// Get stack file
$stackFile = $portainer->stacks()->getFile(1);

// Delete stack
$portainer->stacks()->delete(1, 1);

Kubernetes Management

// Get Kubernetes dashboard
$dashboard = $portainer->kubernetes()->getDashboard(1);

// List namespaces
$namespaces = $portainer->kubernetes()->getNamespaces(1);

// Get namespace by name
$namespace = $portainer->kubernetes()->getNamespace(1, 'default');

// List services
$services = $portainer->kubernetes()->getServices(1, 'default');

// List ingresses
$ingresses = $portainer->kubernetes()->getIngresses(1, 'default');

// Get events
$events = $portainer->kubernetes()->getEvents(1, 'default');

// Check RBAC status
$rbacStatus = $portainer->kubernetes()->isRbacEnabled(1);

Edge Computing

// Edge Groups
$edgeGroups = $portainer->edgeGroups()->list();
$newGroup = $portainer->edgeGroups()->create([
    'name' => 'Production Edge Group',
    'description' => 'Edge group for production environments'
]);

// Edge Jobs
$edgeJobs = $portainer->edgeJobs()->list();
$newJob = $portainer->edgeJobs()->createFromString([
    'name' => 'System Update',
    'script' => 'apt update && apt upgrade -y',
    'edgeGroups' => [1, 2]
]);

// Edge Stacks
$edgeStacks = $portainer->edgeStacks()->list();
$newStack = $portainer->edgeStacks()->createFromFile([
    'name' => 'Web App Stack',
    'stackFileContent' => file_get_contents('docker-compose.yml'),
    'edgeGroups' => [1]
]);

Custom Templates

// List custom templates
$templates = $portainer->customTemplates()->list();

// Create template from file
$template = $portainer->customTemplates()->createFromFile([
    'title' => 'Nginx Web Server',
    'description' => 'High performance web server',
    'fileContent' => file_get_contents('nginx-compose.yml'),
    'type' => 1 // Docker Compose
]);

// Get template file
$fileContent = $portainer->customTemplates()->getFile(1);

Backup and Restore

// Create backup
$backup = $portainer->backup()->create('backup-password');

// Restore from backup
$restore = $portainer->backup()->restore(
    'backup.tar.gz',
    file_get_contents('backup.tar.gz'),
    'backup-password'
);

User Management

// List users
$users = $portainer->users()->list();

// Create user
$newUser = $portainer->users()->create([
    'username' => 'newuser',
    'password' => 'securepassword',
    'role' => 2 // Standard user
]);

// Get current user
$currentUser = $portainer->users()->getCurrent();

// Update user
$portainer->users()->update(1, [
    'username' => 'updateduser'
]);

// Change password
$portainer->users()->changePassword(1, 'newpassword');

Registry Management

// List registries
$registries = $portainer->registries()->list();

// Create registry
$registry = $portainer->registries()->create([
    'name' => 'Private Registry',
    'URL' => 'https://registry.example.com',
    'authentication' => true,
    'username' => 'registry-user',
    'password' => 'registry-password'
]);

// Configure registry access
$portainer->registries()->configureAccess(1, [
    'userAccessPolicies' => [
        [
            'userId' => 1,
            'accessLevel' => 1
        ]
    ]
]);

Settings

// Get settings
$settings = $portainer->settings()->get();

// Update settings
$portainer->settings()->update([
    'logoURL' => 'https://example.com/logo.png',
    'blackListedLabels' => ['production', 'staging']
]);

// Get public settings
$publicSettings = $portainer->settings()->getPublic();

Error Handling

The library uses a custom PortainerException for error handling:

<?php

use Teguh02\PortainerCE\PortainerException;

try {
    $endpoints = $portainer->endpoints()->list();
} catch (PortainerException $e) {
    echo "Error: " . $e->getMessage();
    echo "HTTP Code: " . $e->getCode();
    
    // Get response data if available
    $responseData = $e->getResponseData();
    if ($responseData) {
        print_r($responseData);
    }
}

Authentication Methods

1. Username/Password Authentication

$authResponse = $portainer->auth()->authenticate('admin', 'password');
// Token is automatically set to client

2. OAuth Authentication

$authResponse = $portainer->auth()->validateOAuth('oauth-code');
// Token is automatically set to client

3. Manual Token

$portainer->setJwtToken('your-jwt-token');

4. API Key

$portainer->setApiKey('your-api-key');

Advanced Usage

Custom HTTP Client Options

$portainer = new PortainerClient('http://localhost:9000', [
    'timeout' => 60,
    'verify' => false, // Disable SSL verification
    'headers' => [
        'User-Agent' => 'MyApp/1.0'
    ]
]);

Check Authentication Status

if ($portainer->isAuthenticated()) {
    echo "Client is authenticated";
} else {
    echo "Client is not authenticated";
}

Repository Pattern

The library uses Repository Pattern to organize API calls:

  • auth() - Authentication operations
  • endpoints() - Endpoint management
  • docker() - Docker resources
  • containers() - Container management (start, stop, restart, etc.)
  • stacks() - Stack deployment (Docker Compose)
  • kubernetes() - Kubernetes resources
  • edgeGroups() - Edge groups management
  • edgeJobs() - Edge jobs management
  • edgeStacks() - Edge stacks management
  • customTemplates() - Custom templates
  • backup() - Backup and restore
  • users() - User management
  • registries() - Registry management
  • settings() - Settings management
  • roles() - Role management
  • endpointGroups() - Endpoint groups management

Examples

Check the examples/ directory for comprehensive usage examples:

  • basic-usage.php - Basic library usage
  • container-management.php - Container management examples
  • stack-deployment.php - Stack deployment examples
  • wordpress-deployment.php - WordPress deployment examples
  • kubernetes-management.php - Kubernetes management examples
  • edge-computing.php - Edge computing examples
  • backup-restore.php - Backup and restore examples
  • error-handling.php - Error handling examples

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Testing

# Run tests
composer test

# Run PHPStan
composer phpstan

# Run code style check
composer cs-check

# Fix code style
composer cs-fix

License

This library is licensed under the MIT License.

Support

Changelog

v1.0.0

  • Initial release
  • Support for all Portainer CE API endpoints
  • Repository pattern implementation
  • Comprehensive error handling
  • Full documentation

Made with ❤️ for the Portainer community