PHPackages                             spatie/docker - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [DevOps &amp; Deployment](/categories/devops)
4. /
5. spatie/docker

ActiveLibrary[DevOps &amp; Deployment](/categories/devops)

spatie/docker
=============

Run a docker container in your PHPUnit tests

1.13.1(7mo ago)486135.8k↑61.8%5611MITPHPPHP ^7.4|^8.0CI passing

Since Feb 2Pushed 1mo ago11 watchersCompare

[ Source](https://github.com/spatie/docker)[ Packagist](https://packagist.org/packages/spatie/docker)[ Docs](https://github.com/spatie/docker)[ Fund](https://spatie.be/open-source/support-us)[ RSS](/packages/spatie-docker/feed)WikiDiscussions main Synced yesterday

READMEChangelog (10)Dependencies (6)Versions (23)Used By (11)

Manage docker containers with PHP
=================================

[](#manage-docker-containers-with-php)

[![Latest Version on Packagist](https://camo.githubusercontent.com/b8d0259c3785539926e6ff9144a21f788fde569018e0ba2333dfcb6dcca7f091/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f646f636b65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/docker)[![GitHub Tests Action Status](https://github.com/spatie/docker/actions/workflows/run-tests.yml/badge.svg)](https://github.com/spatie/docker/actions?query=workflow%3Arun-tests+branch%3Amaster)[![Total Downloads](https://camo.githubusercontent.com/63a8f38d2b66e75067ac50c3242a904839bb1022ab90c0f91422fdd9114ba6f9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f646f636b65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/docker)

This package provides a nice way to start docker containers and execute commands on them.

```
$containerInstance = DockerContainer::create($imageName)->start();

$process = $containerInstance->execute('whoami');

$process->getOutput(); // returns the name of the user inside the docker container
```

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/056f4841d66c9dae3dff8fdb9b408a57695ca7f97e8c9e7170c0c2d199551adb/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f646f636b65722e6a70673f743d31)](https://spatie.be/github-ad-click/docker)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require spatie/docker
```

Usage
-----

[](#usage)

You can get an instance of a docker container using

```
$containerInstance = DockerContainer::create($imageName)->start();
```

By default the container will be daemonized and it will be cleaned up after it exists.

### Customizing the docker container

[](#customizing-the-docker-container)

#### Prevent daemonization

[](#prevent-daemonization)

If you don't want your docker being daemonized, call `doNotDaemonize`.

```
$containerInstance = DockerContainer::create($imageName)
    ->doNotDaemonize()
    ->start();
```

#### Prevent automatic clean up

[](#prevent-automatic-clean-up)

If you don't want your docker being cleaned up after it exists, call `doNotCleanUpAfterExit`.

```
$containerInstance = DockerContainer::create($imageName)
    ->doNotCleanUpAfterExit()
    ->start();
```

#### Priviliged

[](#priviliged)

If you want your docker being privileged, call `privileged`.

```
$containerInstance = DockerContainer::create($imageName)
    ->privileged()
    ->start();
```

#### Custom shell

[](#custom-shell)

If the `bash` shell is not available in your docker image, you can specify an alternative shell.

```
$containerInstance = DockerContainer::create($imageName)
    ->shell('sh')
    ->start();
```

#### Custom docker binary

[](#custom-docker-binary)

If the `docker` binary is not globally available, you can specify the exact path.

```
$containerInstance = DockerContainer::create($imageName)
    ->dockerBin('/usr/local/bin/docker')
    ->start();
```

#### Naming the container

[](#naming-the-container)

You can name the container by passing the name as the second argument to the constructor.

```
new DockerContainer($imageName, $nameOfContainer);
```

Alternatively, use the `name` method.

```
$containerInstance = DockerContainer::create($imageName)
    ->name($yourName)
    ->start();
```

#### Mapping ports

[](#mapping-ports)

You can map ports between the host machine and the docker container using the `mapPort` method. To map multiple ports, just call `mapPort` multiple times.

```
$containerInstance = DockerContainer::create($imageName)
    ->mapPort($portOnHost, $portOnContainer)
    ->mapPort($anotherPortOnHost, $anotherPortOnContainer)
    ->start();
```

The default protocol for the port mapping is TCP. If you want to use UDP, you can pass it as the third argument.

```
$containerInstance = DockerContainer::create($imageName)
    ->mapPort($portOnHost, $portOnContainer, 'udp')
    ->start();
```

#### Environment variables

[](#environment-variables)

You can set environment variables using the `setEnvironmentVariable` method. To add multiple arguments, just call `setEnvironmentVariable` multiple times.

```
$containerInstance = DockerContainer::create($imageName)
    ->setEnvironmentVariable($variableKey, $variableValue)
    ->setEnvironmentVariable($anotherVariableKey, $anotherVariableValue)
    ->start();
```

#### Setting Volumes

[](#setting-volumes)

You can set volumes using the `setVolume` method. To add multiple arguments, just call `setVolume` multiple times.

```
$containerInstance = DockerContainer::create($imageName)
    ->setVolume($pathOnHost, $pathOnDocker)
    ->setVolume($anotherPathOnHost, $anotherPathOnDocker)
    ->start();
```

#### Setting Labels

[](#setting-labels)

You can set labels using the `setLabel` method. To add multiple arguments, just call `setLabel` multiple times.

```
$containerInstance = DockerContainer::create($imageName)
    ->setLabel($labelName, $labelValue)
    ->setLabel($anotherLabelName, $anotherLabelValue)
    ->start();
```

#### Adding Commands

[](#adding-commands)

You can add commands using the `setCommands` method.

```
$containerInstance = DockerContainer::create($imageName)
    ->setCommands('--api.insecure=true', '--providers.docker=true')
    ->start();
```

These commands will be placed at the end of to the `docker run` command.

#### Add optional arguments

[](#add-optional-arguments)

If you want to add optional arguments to the `docker run` command, use `setOptionalArgs` method:

```
$containerInstance = DockerContainer::create($imageName)
    ->setOptionalArgs('-it', '-a')
    ->start();
```

These arguments will be placed after `docker run` immediately.

#### Automatically stopping the container after PHP exists

[](#automatically-stopping-the-container-after-php-exists)

When using this package in a testing environment, it can be handy that the docker container is stopped after `__destruct` is called on it (mostly this will happen when the PHP script ends). You can enable this behaviour with the `stopOnDestruct` method.

```
$containerInstance = DockerContainer::create($imageName)
    ->stopOnDestruct()
    ->start();
```

#### Attaching a network to the container

[](#attaching-a-network-to-the-container)

If you want to attach the container to a docker network, use `network` method:

```
$containerInstance = DockerContainer::create($imageName)
    ->network('my-network')
    ->start();
```

#### Specify a remote docker host for execution

[](#specify-a-remote-docker-host-for-execution)

You can set the host used for executing the container. The `docker` command line accepts a daemon socket string. To connect to a remote docker host via ssh, use the syntax `ssh://username@hostname`. Note that the proper SSH keys will already need to be configured for this work.

```
$containerInstance = DockerContainer::create($imageName)
    ->remoteHost('ssh://username@hostname')
    ->start();
```

#### Specify an alternative command to execute

[](#specify-an-alternative-command-to-execute)

Upon startup of a container, docker will execute the command defined within the container. The `command` method gives the ability to override to default command to run within the container.

```
$containerInstance = DockerContainer::create($imageName)
    ->command('ls -l /etc')
    ->start();
```

#### Getting the start command string

[](#getting-the-start-command-string)

You can get the string that will be executed when a container is started with the `getStartCommand` function

```
// returns "docker run -d --rm spatie/docker"
DockerContainer::create($imageName)->getStartCommand();
```

#### Changing the start command timeout

[](#changing-the-start-command-timeout)

You can change the timeout for the start command with the `setStartCommandTimeout` function *(the default is 60s)*.

```
$containerInstance = DockerContainer::create($imageName)
    ->setStartCommandTimeout(120)
    ->start();
```

### Available methods on the docker container instance

[](#available-methods-on-the-docker-container-instance)

#### Executing a command

[](#executing-a-command)

To execute a command on the container, use the `execute` method.

```
$process = $instance->execute($command);
```

You can execute multiple command in one go by passing an array.

```
$process = $instance->execute([$command, $anotherCommand]);
```

To change the process timeout you can pass a second parameter to the `execute` method *(the default is 60s)*.

```
$process = $instance->execute($command, 3600);
```

The execute method returns an instance of [`Symfony/Process`](https://symfony.com/doc/current/components/process.html).

You can check if your command ran successfully using the `isSuccessful` $method

```
$process->isSuccessful(); // returns a boolean
```

You can get to the output using `getOutput()`. If the command did not run successfully, you can use `getErrorOutput()`. For more information on how to work with a `Process` head over to [the Symfony docs](https://symfony.com/doc/current/components/process.html).

#### Installing a public key

[](#installing-a-public-key)

If you cant to connect to your container instance via SSH, you probably want to add a public key to it.

This can be done using the `addPublicKey` method.

```
$instance->addPublicKey($pathToPublicKey);
```

It is assumed that the `authorized_keys` file is located in at `/root/.ssh/authorized_keys`. If this is not the case, you can specify the path of that file as a second parameter.

```
$instance->addPublicKey($pathToPublicKey, $pathToAuthorizedKeys);
```

Note that in order to be able to connect via SSH, you should set up a SSH server in your `dockerfile`. Take a look at the `dockerfile` in the tests of this package for an example.

#### Adding files to your instance

[](#adding-files-to-your-instance)

Files can be added to an instance with `addFiles`.

```
$instance->addFiles($fileOrDirectoryOnHost, $pathInContainer);
```

#### Get the docker inspect information

[](#get-the-docker-inspect-information)

The json decoded array from the docker inspect command can be retrieved with `inspect`.

```
$inspectArray = $instance->inspect();
$inspectArray[0]['State']['Status']; // Running, Starting etc.
$inspectArray[0]['RestartCount']; // Integer
$inspectArray[0]['NetworkSettings']['IPAddress']; // 172.17.0.2
```

#### Adding other functions on the docker instance

[](#adding-other-functions-on-the-docker-instance)

The `Spatie\Docker\ContainerInstance` class is [macroable](https://github.com/spatie/macroable). This means you can add extra functions to it.

```
Spatie\Docker\DockerContainerInstance::macro('whoAmI', function () {
    $process = $containerInstance->run('whoami');

    return $process->getOutput();
});

$containerInstance = DockerContainer::create($imageName)->start();

$containerInstance->whoAmI(); // returns of name of user in the docker container
```

### Testing

[](#testing)

Before running the tests for the first time, you must build the `spatie/docker` container with:

```
composer build-docker
```

Next, you can run the tests with:

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you've found a bug regarding security please mail  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Ruben Van Assche](https://github.com/rubenvanassche)
- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

64

—

FairBetter than 99% of packages

Maintenance81

Actively maintained with recent releases

Popularity55

Moderate usage in the ecosystem

Community39

Small or concentrated contributor base

Maturity72

Established project with proven stability

 Bus Factor1

Top contributor holds 56.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~106 days

Recently: every ~249 days

Total

21

Last Release

219d ago

Major Versions

0.0.1 → 1.0.02020-02-04

PHP version history (3 changes)0.0.1PHP ^7.4

1.5.0PHP ^7.4 || ^8.0

1.7.1PHP ^7.4|^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (119 commits)")[![rubenvanassche](https://avatars.githubusercontent.com/u/619804?v=4)](https://github.com/rubenvanassche "rubenvanassche (18 commits)")[![jbraband](https://avatars.githubusercontent.com/u/1907283?v=4)](https://github.com/jbraband "jbraband (9 commits)")[![patinthehat](https://avatars.githubusercontent.com/u/5508707?v=4)](https://github.com/patinthehat "patinthehat (9 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (8 commits)")[![Galironfydar](https://avatars.githubusercontent.com/u/13006625?v=4)](https://github.com/Galironfydar "Galironfydar (7 commits)")[![jkniest](https://avatars.githubusercontent.com/u/15618191?v=4)](https://github.com/jkniest "jkniest (4 commits)")[![m1guelpf](https://avatars.githubusercontent.com/u/23558090?v=4)](https://github.com/m1guelpf "m1guelpf (3 commits)")[![joelambert](https://avatars.githubusercontent.com/u/644362?v=4)](https://github.com/joelambert "joelambert (3 commits)")[![AyoobMH](https://avatars.githubusercontent.com/u/37803924?v=4)](https://github.com/AyoobMH "AyoobMH (2 commits)")[![rconfig](https://avatars.githubusercontent.com/u/20505440?v=4)](https://github.com/rconfig "rconfig (2 commits)")[![szepeviktor](https://avatars.githubusercontent.com/u/952007?v=4)](https://github.com/szepeviktor "szepeviktor (2 commits)")[![thecaliskan](https://avatars.githubusercontent.com/u/13554944?v=4)](https://github.com/thecaliskan "thecaliskan (2 commits)")[![tiagof](https://avatars.githubusercontent.com/u/1729910?v=4)](https://github.com/tiagof "tiagof (2 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (2 commits)")[![vedelaar](https://avatars.githubusercontent.com/u/41993858?v=4)](https://github.com/vedelaar "vedelaar (2 commits)")[![wajdijurry](https://avatars.githubusercontent.com/u/25797257?v=4)](https://github.com/wajdijurry "wajdijurry (2 commits)")[![maartenpaauw](https://avatars.githubusercontent.com/u/4550875?v=4)](https://github.com/maartenpaauw "maartenpaauw (2 commits)")[![tomwelch](https://avatars.githubusercontent.com/u/1016558?v=4)](https://github.com/tomwelch "tomwelch (1 commits)")[![exileed](https://avatars.githubusercontent.com/u/942898?v=4)](https://github.com/exileed "exileed (1 commits)")

---

Tags

dockerphpspatiedocker

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/spatie-docker/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-docker/health.svg)](https://phpackages.com/packages/spatie-docker)
```

###  Alternatives

[matomo/matomo

Matomo is the leading Free/Libre open analytics platform

21.7k38.9k](/packages/matomo-matomo)[spatie/dns

Retrieve DNS records

6092.7M22](/packages/spatie-dns)[spatie/laravel-health

Monitor the health of a Laravel application

87512.0M165](/packages/spatie-laravel-health)[spatie/flare-client-php

Send PHP errors to Flare

177161.5M23](/packages/spatie-flare-client-php)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k15](/packages/tempest-framework)[spatie/typescript-transformer

This is my package typescript-transformer

3957.8M25](/packages/spatie-typescript-transformer)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
