Skip to main content
Glama

Create and Run Docker Containers

create_container

Create and run Docker containers with configurable options for ports, volumes, environment variables, networks, and resource management.

Instructions

Create and run Docker containers with advanced options

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
imageYesDocker image to run
nameNoContainer name
portsNoPort mappings (e.g., ['8080:80', '3000:3000'])
volumesNoVolume mounts (e.g., ['/host/path:/container/path'])
environmentNoEnvironment variables
networkNoNetwork to connect to
detachedNoRun in detached mode
interactiveNoRun in interactive mode
commandNoCommand to run in container
workdirNoWorking directory
restartNoRestart policy
healthCheckNoHealth check configuration
resourcesNoResource constraints
securityNoSecurity options
labelsNoContainer labels
hostnameNoContainer hostname
domainnameNoContainer domain name
projectNameNoProject name for resource grouping

Implementation Reference

  • The handler function for the create_container tool. It constructs a docker run command based on the provided parameters (image, ports, volumes, env, etc.) including advanced options like health checks, resources, security, and executes it using executeDockerCommand.
    async ({ image, name, ports, volumes, environment, network, detached, interactive, command, workdir, restart, healthCheck, resources, security, labels, hostname, domainname, projectName }) => {
      try {
        let dockerCommand = "docker run";
        
        // Add flags
        if (detached && !interactive) dockerCommand += " -d";
        if (interactive) dockerCommand += " -it";
        if (name) dockerCommand += ` --name ${name}`;
        
        // Add port mappings
        if (ports && ports.length > 0) {
          ports.forEach(port => {
            dockerCommand += ` -p ${port}`;
          });
        }
        
        // Add volume mounts
        if (volumes && volumes.length > 0) {
          volumes.forEach(volume => {
            dockerCommand += ` -v ${volume}`;
          });
        }
        
        // Add environment variables
        if (environment) {
          Object.entries(environment).forEach(([key, value]) => {
            dockerCommand += ` -e ${key}=${value}`;
          });
        }
        
        // Add network
        if (network) dockerCommand += ` --network ${network}`;
        
        // Add working directory
        if (workdir) dockerCommand += ` -w ${workdir}`;
        
        // Add restart policy
        if (restart) dockerCommand += ` --restart ${restart}`;
        
        // Add hostname
        if (hostname) dockerCommand += ` --hostname ${hostname}`;
        
        // Add domain name
        if (domainname) dockerCommand += ` --domainname ${domainname}`;
        
        // Add health check
        if (healthCheck) {
          dockerCommand += ` --health-cmd "${healthCheck.test}"`;
          if (healthCheck.interval) dockerCommand += ` --health-interval ${healthCheck.interval}`;
          if (healthCheck.timeout) dockerCommand += ` --health-timeout ${healthCheck.timeout}`;
          if (healthCheck.retries) dockerCommand += ` --health-retries ${healthCheck.retries}`;
        }
        
        // Add resource constraints
        if (resources) {
          if (resources.memory) dockerCommand += ` --memory ${resources.memory}`;
          if (resources.cpus) dockerCommand += ` --cpus ${resources.cpus}`;
          if (resources.memorySwap) dockerCommand += ` --memory-swap ${resources.memorySwap}`;
        }
        
        // Add security options
        if (security) {
          if (security.user) dockerCommand += ` --user ${security.user}`;
          if (security.readOnly) dockerCommand += " --read-only";
          if (security.tmpfs) {
            security.tmpfs.forEach(tmpfs => {
              dockerCommand += ` --tmpfs ${tmpfs}`;
            });
          }
        }
        
        // Add labels
        if (labels) {
          Object.entries(labels).forEach(([key, value]) => {
            dockerCommand += ` --label "${key}=${value}"`;
          });
        }
        
        // Add image
        dockerCommand += ` ${image}`;
        
        // Add command
        if (command) dockerCommand += ` ${command}`;
        
        // Add project label if specified
        if (projectName) {
          dockerCommand = ProjectManager.addProjectLabel(dockerCommand, projectName);
        }
        
        const result = await executeDockerCommand(dockerCommand);
        
        return {
          content: [
            {
              type: "text",
              text: `Container created successfully:\n\nCommand: ${dockerCommand}\n\nOutput:\n${result.stdout}${result.stderr ? `\nWarnings:\n${result.stderr}` : ""}`
            }
          ]
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Error creating container: ${error instanceof Error ? error.message : String(error)}`
            }
          ],
          isError: true
        };
      }
    }
  • The input schema definition for the create_container tool, using Zod for validation of parameters like image, ports, volumes, environment variables, advanced options such as healthCheck, resources, security, etc.
    {
      title: "Create and Run Docker Containers",
      description: "Create and run Docker containers with advanced options",
      inputSchema: {
        image: z.string().describe("Docker image to run"),
        name: z.string().optional().describe("Container name"),
        ports: z.array(z.string()).optional().describe("Port mappings (e.g., ['8080:80', '3000:3000'])"),
        volumes: z.array(z.string()).optional().describe("Volume mounts (e.g., ['/host/path:/container/path'])"),
        environment: z.record(z.string()).optional().describe("Environment variables"),
        network: z.string().optional().describe("Network to connect to"),
        detached: z.boolean().optional().default(true).describe("Run in detached mode"),
        interactive: z.boolean().optional().default(false).describe("Run in interactive mode"),
        command: z.string().optional().describe("Command to run in container"),
        workdir: z.string().optional().describe("Working directory"),
        restart: z.enum(["no", "on-failure", "always", "unless-stopped"]).optional().describe("Restart policy"),
        // Advanced options
        healthCheck: z.object({
          test: z.string(),
          interval: z.string().optional(),
          timeout: z.string().optional(),
          retries: z.number().optional()
        }).optional().describe("Health check configuration"),
        resources: z.object({
          memory: z.string().optional(),
          cpus: z.string().optional(),
          memorySwap: z.string().optional()
        }).optional().describe("Resource constraints"),
        security: z.object({
          user: z.string().optional(),
          readOnly: z.boolean().optional(),
          tmpfs: z.array(z.string()).optional()
        }).optional().describe("Security options"),
        labels: z.record(z.string()).optional().describe("Container labels"),
        hostname: z.string().optional().describe("Container hostname"),
        domainname: z.string().optional().describe("Container domain name"),
        projectName: z.string().optional().describe("Project name for resource grouping")
      }
  • src/index.ts:1504-1656 (registration)
    The registration of the create_container tool on the MCP server, including the tool name, schema, and handler function.
    // Register Docker container creation and management tool
    server.registerTool(
      "create_container",
      {
        title: "Create and Run Docker Containers",
        description: "Create and run Docker containers with advanced options",
        inputSchema: {
          image: z.string().describe("Docker image to run"),
          name: z.string().optional().describe("Container name"),
          ports: z.array(z.string()).optional().describe("Port mappings (e.g., ['8080:80', '3000:3000'])"),
          volumes: z.array(z.string()).optional().describe("Volume mounts (e.g., ['/host/path:/container/path'])"),
          environment: z.record(z.string()).optional().describe("Environment variables"),
          network: z.string().optional().describe("Network to connect to"),
          detached: z.boolean().optional().default(true).describe("Run in detached mode"),
          interactive: z.boolean().optional().default(false).describe("Run in interactive mode"),
          command: z.string().optional().describe("Command to run in container"),
          workdir: z.string().optional().describe("Working directory"),
          restart: z.enum(["no", "on-failure", "always", "unless-stopped"]).optional().describe("Restart policy"),
          // Advanced options
          healthCheck: z.object({
            test: z.string(),
            interval: z.string().optional(),
            timeout: z.string().optional(),
            retries: z.number().optional()
          }).optional().describe("Health check configuration"),
          resources: z.object({
            memory: z.string().optional(),
            cpus: z.string().optional(),
            memorySwap: z.string().optional()
          }).optional().describe("Resource constraints"),
          security: z.object({
            user: z.string().optional(),
            readOnly: z.boolean().optional(),
            tmpfs: z.array(z.string()).optional()
          }).optional().describe("Security options"),
          labels: z.record(z.string()).optional().describe("Container labels"),
          hostname: z.string().optional().describe("Container hostname"),
          domainname: z.string().optional().describe("Container domain name"),
          projectName: z.string().optional().describe("Project name for resource grouping")
        }
      },
      async ({ image, name, ports, volumes, environment, network, detached, interactive, command, workdir, restart, healthCheck, resources, security, labels, hostname, domainname, projectName }) => {
        try {
          let dockerCommand = "docker run";
          
          // Add flags
          if (detached && !interactive) dockerCommand += " -d";
          if (interactive) dockerCommand += " -it";
          if (name) dockerCommand += ` --name ${name}`;
          
          // Add port mappings
          if (ports && ports.length > 0) {
            ports.forEach(port => {
              dockerCommand += ` -p ${port}`;
            });
          }
          
          // Add volume mounts
          if (volumes && volumes.length > 0) {
            volumes.forEach(volume => {
              dockerCommand += ` -v ${volume}`;
            });
          }
          
          // Add environment variables
          if (environment) {
            Object.entries(environment).forEach(([key, value]) => {
              dockerCommand += ` -e ${key}=${value}`;
            });
          }
          
          // Add network
          if (network) dockerCommand += ` --network ${network}`;
          
          // Add working directory
          if (workdir) dockerCommand += ` -w ${workdir}`;
          
          // Add restart policy
          if (restart) dockerCommand += ` --restart ${restart}`;
          
          // Add hostname
          if (hostname) dockerCommand += ` --hostname ${hostname}`;
          
          // Add domain name
          if (domainname) dockerCommand += ` --domainname ${domainname}`;
          
          // Add health check
          if (healthCheck) {
            dockerCommand += ` --health-cmd "${healthCheck.test}"`;
            if (healthCheck.interval) dockerCommand += ` --health-interval ${healthCheck.interval}`;
            if (healthCheck.timeout) dockerCommand += ` --health-timeout ${healthCheck.timeout}`;
            if (healthCheck.retries) dockerCommand += ` --health-retries ${healthCheck.retries}`;
          }
          
          // Add resource constraints
          if (resources) {
            if (resources.memory) dockerCommand += ` --memory ${resources.memory}`;
            if (resources.cpus) dockerCommand += ` --cpus ${resources.cpus}`;
            if (resources.memorySwap) dockerCommand += ` --memory-swap ${resources.memorySwap}`;
          }
          
          // Add security options
          if (security) {
            if (security.user) dockerCommand += ` --user ${security.user}`;
            if (security.readOnly) dockerCommand += " --read-only";
            if (security.tmpfs) {
              security.tmpfs.forEach(tmpfs => {
                dockerCommand += ` --tmpfs ${tmpfs}`;
              });
            }
          }
          
          // Add labels
          if (labels) {
            Object.entries(labels).forEach(([key, value]) => {
              dockerCommand += ` --label "${key}=${value}"`;
            });
          }
          
          // Add image
          dockerCommand += ` ${image}`;
          
          // Add command
          if (command) dockerCommand += ` ${command}`;
          
          // Add project label if specified
          if (projectName) {
            dockerCommand = ProjectManager.addProjectLabel(dockerCommand, projectName);
          }
          
          const result = await executeDockerCommand(dockerCommand);
          
          return {
            content: [
              {
                type: "text",
                text: `Container created successfully:\n\nCommand: ${dockerCommand}\n\nOutput:\n${result.stdout}${result.stderr ? `\nWarnings:\n${result.stderr}` : ""}`
              }
            ]
          };
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Error creating container: ${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 the full burden of behavioral disclosure. 'Create and run' implies a write/mutation operation, but the description doesn't mention permissions required, whether containers persist after execution, error handling, or what happens if a container with the same name exists. For a complex 18-parameter mutation tool, this is a significant gap in behavioral context.

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 a single, efficient sentence that gets straight to the point. 'Create and run Docker containers with advanced options' contains no wasted words and immediately communicates the core functionality. It's appropriately sized for what it conveys.

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?

For a complex mutation tool with 18 parameters, no annotations, and no output schema, the description is inadequate. It doesn't address behavioral aspects like permissions, side effects, or error conditions. While the schema covers parameters well, the description fails to provide the contextual understanding needed for safe and effective tool invocation in a Docker management ecosystem with multiple similar tools.

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 the schema already documents all 18 parameters thoroughly. The description adds no additional parameter information beyond what's in the schema - it doesn't explain parameter relationships, constraints, or provide examples beyond the schema's descriptions. The baseline of 3 is appropriate when the schema does all the parameter documentation work.

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 action ('create and run') and resource ('Docker containers'), making the purpose understandable. However, it doesn't differentiate this tool from sibling tools like 'manage_containers' or 'docker_compose', which likely have overlapping functionality. The phrase 'with advanced options' adds some specificity but doesn't clearly demarcate boundaries.

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. With multiple sibling tools like 'manage_containers', 'docker_compose', and 'execute_docker_command', there's no indication of when this specific container creation tool is appropriate versus those other options. The agent receives no usage context.

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