Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Docker Laravel Package

spatie/docker

Start and manage Docker containers from PHP. Create and run containers, execute commands inside them, and capture output. Customize behavior like daemonization, auto-cleanup on exit, and privileged mode for more control.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/docker
    

    Requires Docker to be installed and running on your system.

  2. First Use Case: Start a container and execute a command:

    use Spatie\Docker\DockerContainer;
    
    $container = DockerContainer::create('alpine:latest')
        ->start();
    
    $output = $container->execute('echo "Hello Docker!"')->getOutput();
    echo $output; // "Hello Docker!"
    
  3. Where to Look First:


Implementation Patterns

Common Workflows

1. Test Environments

Spin up disposable containers for PHPUnit tests (e.g., databases, services):

use Spatie\Docker\DockerContainer;

beforeEach(function () {
    $this->container = DockerContainer::create('mysql:8.0')
        ->withPorts(['3306:3306'])
        ->withEnvironment(['MYSQL_ROOT_PASSWORD' => 'secret'])
        ->start();
});

afterEach(function () {
    $this->container->stop();
});

2. Command Execution

Run commands inside containers (e.g., migrations, CLI tools):

$container = DockerContainer::create('composer:latest')->start();
$output = $container->execute('composer install')->getOutput();

3. Resource Management

Reuse containers across tests or scripts:

$container = DockerContainer::create('redis:alpine')
    ->start()
    ->stop(); // Stop when done

4. Integration with Laravel

Use in Artisan commands or service providers:

use Spatie\Docker\DockerContainer;

class DeployCommand extends Command
{
    protected $signature = 'deploy:docker';
    public function handle()
    {
        $container = DockerContainer::create('your-app-image')->start();
        $container->execute('php artisan migrate');
    }
}

5. Dynamic Container Configuration

Build containers with custom options:

$container = DockerContainer::create('node:18')
    ->withWorkingDirectory('/app')
    ->withMountedDirectory('/local/path', '/container/path')
    ->start();

Integration Tips

  • Error Handling: Wrap container operations in try-catch blocks to handle DockerException:

    try {
        $container->start();
    } catch (DockerException $e) {
        Log::error('Docker failed: ' . $e->getMessage());
    }
    
  • Environment Variables: Pass secrets or configs via withEnvironment():

    ->withEnvironment([
        'DB_HOST' => 'localhost',
        'APP_KEY' => env('APP_KEY'),
    ])
    
  • Port Mapping: Expose ports for local development or testing:

    ->withPorts(['8000:80'])
    
  • Logging: Stream container logs in real-time:

    $container->start();
    $container->logs(function ($output) {
        echo $output;
    });
    

Gotchas and Tips

Pitfalls

  1. Docker Daemon Access:

    • Ensure your PHP process has permission to interact with Docker (e.g., user is in the docker group on Linux).
    • On CI/CD, use docker:dind (Docker-in-Docker) if Docker isn’t pre-installed.
  2. Resource Limits:

    • Containers consume host resources. Clean up with stop() or remove() after use:
      $container->stop()->remove();
      
  3. Image Availability:

    • Verify the image exists locally or is pullable:
      if (!$container->imageExists()) {
          $container->pull();
      }
      
  4. Command Timeouts:

    • Long-running commands may time out. Adjust with withTimeout():
      ->execute('long-running-command', 300) // 5-minute timeout
      
  5. Port Conflicts:

    • Avoid port clashes by using dynamic host ports:
      ->withPorts(['0:80']) // Random host port
      

Debugging

  • Inspect Container: Use getInspection() to debug container state:

    $inspection = $container->getInspection();
    dd($inspection['State']); // Check 'Running', 'ExitCode', etc.
    
  • Logs: Capture logs for troubleshooting:

    $logs = $container->getLogs();
    
  • Process Output: Check raw output (stdout/stderr) separately:

    $process = $container->execute('ls /nonexistent');
    $process->getOutput(); // stdout
    $process->getErrorOutput(); // stderr
    

Tips

  1. Reuse Containers: Cache container instances for repeated use (e.g., in tests):

    static $redisContainer;
    if (!$redisContainer) {
        $redisContainer = DockerContainer::create('redis:alpine')->start();
    }
    
  2. Custom Entrypoints: Override container entrypoints:

    ->withEntrypoint(['/custom-script.sh'])
    
  3. Volume Mounts: Persist data between container runs:

    ->withMountedDirectory('/host/path', '/container/path')
    
  4. Health Checks: Verify container readiness before use:

    $container->start();
    if (!$container->isRunning()) {
        throw new RuntimeException('Container failed to start');
    }
    
  5. Cleanup: Automate cleanup in afterEach() (tests) or finally blocks:

    try {
        $container->start();
        // ... use container ...
    } finally {
        $container->stop()->remove();
    }
    
  6. Networking: Connect containers to custom networks:

    ->withNetwork('your-network-name')
    
  7. Platform-Specific Quirks:

    • Windows: Use npipe for Docker Desktop interactions.
    • CI/CD: Ensure DOCKER_HOST is set if using remote Docker daemons.
  8. Performance: Reuse images to avoid repeated pulls:

    $container->pullIfNotExists();
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4