Skip to main content
Glama

Docker Backup and Migration

docker_backup_migration

Backup Docker containers, volumes, and projects for migration or disaster recovery. Export projects, manage backup files, and clean up old backups to maintain storage efficiency.

Instructions

Backup containers, volumes, and entire projects for migration

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
actionYesBackup action
containerNameNoContainer name (required for backup_container)
projectNameNoProject name (required for export_project)
backupPathNoBackup destination path
daysNoDays to keep backups (for cleanup)

Implementation Reference

  • Primary handler function for the docker_backup_migration tool. It processes the input parameters, sets default backup path, and dispatches to specific actions: backup_container (calls DockerBackup.backupContainer), export_project (calls DockerBackup.exportProject), list_backups, cleanup_backups. Returns formatted content or error.
    async ({ action, containerName, projectName, backupPath, days }) => {
      try {
        const defaultBackupPath = "/tmp/docker-backups";
        const path = backupPath || defaultBackupPath;
        
        switch (action) {
          case "backup_container":
            if (!containerName) {
              throw new Error("Container name is required for backup");
            }
            
            const backupResult = await DockerBackup.backupContainer(containerName, path);
            return {
              content: [
                {
                  type: "text",
                  text: `## Container Backup Complete\n\n${backupResult}`
                }
              ]
            };
    
          case "export_project":
            if (!projectName) {
              throw new Error("Project name is required for export");
            }
            
            const exportResult = await DockerBackup.exportProject(projectName, path);
            return {
              content: [
                {
                  type: "text",
                  text: exportResult
                }
              ]
            };
    
          case "list_backups":
            const listResult = await executeDockerCommand(`find ${path} -name "*.tar" -o -name "*-config.json" | head -20`);
            return {
              content: [
                {
                  type: "text",
                  text: `## Available Backups\n\n\`\`\`\n${listResult.stdout || 'No backups found'}\n\`\`\``
                }
              ]
            };
    
          case "cleanup_backups":
            const cleanupDays = days || 7;
            const cleanupResult = await executeDockerCommand(`find ${path} -type f -mtime +${cleanupDays} -delete`);
            return {
              content: [
                {
                  type: "text",
                  text: `✅ Cleaned up backups older than ${cleanupDays} days from ${path}`
                }
              ]
            };
        }
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Error with backup/migration: ${error instanceof Error ? error.message : String(error)}`
            }
          ],
          isError: true
        };
      }
    }
  • DockerBackup class providing helper methods: backupContainer (exports container to tar, saves inspect JSON, backs up volumes using alpine tar), exportProject (gets project resources, calls backupContainer on each, saves metadata JSON). Used by the tool handler.
    class DockerBackup {
      static async backupContainer(containerName: string, backupPath: string): Promise<string> {
        const results: string[] = [];
        
        try {
          // Create backup directory
          await executeDockerCommand(`mkdir -p ${backupPath}`);
          
          // Export container as tar
          const exportResult = await executeDockerCommand(`docker export ${containerName} > ${backupPath}/${containerName}-backup.tar`);
          results.push(`✅ Exported container ${containerName} to ${backupPath}/${containerName}-backup.tar`);
          
          // Get container config
          const inspectResult = await executeDockerCommand(`docker inspect ${containerName}`);
          const configPath = `${backupPath}/${containerName}-config.json`;
          await executeDockerCommand(`echo '${inspectResult.stdout}' > ${configPath}`);
          results.push(`✅ Saved container configuration to ${configPath}`);
          
          // Backup volumes if any
          const config = JSON.parse(inspectResult.stdout)[0];
          const mounts = config.Mounts || [];
          
          for (const mount of mounts) {
            if (mount.Type === 'volume') {
              const volumeBackupPath = `${backupPath}/${mount.Name}-volume.tar`;
              await executeDockerCommand(`docker run --rm -v ${mount.Name}:/volume -v ${backupPath}:/backup alpine tar czf /backup/${mount.Name}-volume.tar -C /volume .`);
              results.push(`✅ Backed up volume ${mount.Name} to ${volumeBackupPath}`);
            }
          }
          
          return results.join('\n');
        } catch (error) {
          throw new Error(`Backup failed: ${error instanceof Error ? error.message : String(error)}`);
        }
      }
    
      static async exportProject(projectName: string, exportPath: string): Promise<string> {
        const results: string[] = [];
        const resources = await ProjectManager.getProjectResources(projectName);
        
        try {
          // Create export directory
          await executeDockerCommand(`mkdir -p ${exportPath}/${projectName}`);
          
          // Export each container
          for (const container of resources.containers) {
            const containerName = container.Names || container.name;
            await this.backupContainer(containerName, `${exportPath}/${projectName}`);
            results.push(`✅ Exported container ${containerName}`);
          }
          
          // Export project metadata
          const metadata = {
            projectName,
            exportDate: new Date().toISOString(),
            resources: {
              containers: resources.containers.length,
              networks: resources.networks.length,
              volumes: resources.volumes.length
            }
          };
          
          await executeDockerCommand(`echo '${JSON.stringify(metadata, null, 2)}' > ${exportPath}/${projectName}/project-metadata.json`);
          results.push(`✅ Exported project metadata`);
          
          return `## Project Export Complete\n\n${results.join('\n')}\n\nProject ${projectName} has been exported to ${exportPath}/${projectName}`;
        } catch (error) {
          throw new Error(`Export failed: ${error instanceof Error ? error.message : String(error)}`);
        }
      }
    }
  • Zod input schema defining the tool's parameters with descriptions and optionality.
    inputSchema: {
      action: z.enum(["backup_container", "export_project", "list_backups", "cleanup_backups"]).describe("Backup action"),
      containerName: z.string().optional().describe("Container name (required for backup_container)"),
      projectName: z.string().optional().describe("Project name (required for export_project)"),
      backupPath: z.string().optional().describe("Backup destination path"),
      days: z.number().optional().describe("Days to keep backups (for cleanup)")
    }
  • src/index.ts:895-979 (registration)
    MCP tool registration call that associates the name 'docker_backup_migration' with its schema and handler implementation.
    server.registerTool(
      "docker_backup_migration",
      {
        title: "Docker Backup and Migration",
        description: "Backup containers, volumes, and entire projects for migration",
        inputSchema: {
          action: z.enum(["backup_container", "export_project", "list_backups", "cleanup_backups"]).describe("Backup action"),
          containerName: z.string().optional().describe("Container name (required for backup_container)"),
          projectName: z.string().optional().describe("Project name (required for export_project)"),
          backupPath: z.string().optional().describe("Backup destination path"),
          days: z.number().optional().describe("Days to keep backups (for cleanup)")
        }
      },
      async ({ action, containerName, projectName, backupPath, days }) => {
        try {
          const defaultBackupPath = "/tmp/docker-backups";
          const path = backupPath || defaultBackupPath;
          
          switch (action) {
            case "backup_container":
              if (!containerName) {
                throw new Error("Container name is required for backup");
              }
              
              const backupResult = await DockerBackup.backupContainer(containerName, path);
              return {
                content: [
                  {
                    type: "text",
                    text: `## Container Backup Complete\n\n${backupResult}`
                  }
                ]
              };
    
            case "export_project":
              if (!projectName) {
                throw new Error("Project name is required for export");
              }
              
              const exportResult = await DockerBackup.exportProject(projectName, path);
              return {
                content: [
                  {
                    type: "text",
                    text: exportResult
                  }
                ]
              };
    
            case "list_backups":
              const listResult = await executeDockerCommand(`find ${path} -name "*.tar" -o -name "*-config.json" | head -20`);
              return {
                content: [
                  {
                    type: "text",
                    text: `## Available Backups\n\n\`\`\`\n${listResult.stdout || 'No backups found'}\n\`\`\``
                  }
                ]
              };
    
            case "cleanup_backups":
              const cleanupDays = days || 7;
              const cleanupResult = await executeDockerCommand(`find ${path} -type f -mtime +${cleanupDays} -delete`);
              return {
                content: [
                  {
                    type: "text",
                    text: `✅ Cleaned up backups older than ${cleanupDays} days from ${path}`
                  }
                ]
              };
          }
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Error with backup/migration: ${error instanceof Error ? error.message : String(error)}`
              }
            ],
            isError: true
          };
        }
      }
    );
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions backup and migration but doesn't describe what 'backup' entails (e.g., creates files, requires storage space), whether operations are destructive, authentication needs, rate limits, or what happens during migration. This is inadequate for a tool with multiple action types.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise with a single sentence that efficiently communicates the core functionality. Every word earns its place, and it's front-loaded with the main purpose without unnecessary elaboration.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (multiple action types, 5 parameters) and lack of both annotations and output schema, the description is insufficient. It doesn't explain what the tool returns, error conditions, or behavioral details needed for safe operation, leaving significant gaps for an AI agent.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so parameters are well-documented in the schema. The description adds no additional parameter semantics beyond implying the tool handles containers, volumes, and projects, which aligns with the 'action' enum values. This meets the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose as backing up and migrating Docker resources (containers, volumes, projects). It uses specific verbs ('backup', 'migration') and resources, but doesn't explicitly differentiate from sibling tools like 'manage_containers' or 'manage_volumes' that might handle similar operations.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites, when not to use it, or how it differs from sibling tools like 'manage_containers' or 'docker_compose' that might handle related backup or migration tasks.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/TauqeerAhmad5201/docker-mcp-extension'

If you have feedback or need assistance with the MCP directory API, please join our Discord server