### Complete Generic Container Configuration Example Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/configuration.md A comprehensive example demonstrating the setup of a GenericContainer in PHP, including Docker client configuration, environment variables, labels, file system binds, working directory, startup timeouts, auto-removal, reuse mode, image pull policy, startup check strategy, and wait strategy. ```php use Testcontainers\Testcontainers; use Testcontainers\Containers\GenericContainer\GenericContainer; use Testcontainers\Containers\ReuseMode; use Testcontainers\Containers\Types\BindMode; use Testcontainers\Containers\Types\ImagePullPolicy; use Testcontainers\Containers\StartupCheckStrategy\IsRunningStartupCheckStrategy; use Testcontainers\Containers\WaitStrategy\LogMessageWaitStrategy; use Testcontainers\Docker\DockerClientFactory; // Configure Docker client globally DockerClientFactory::config([ 'timeout' => 120, 'globalOptions' => ['--config' => '/custom/config'] ]); class AppContainer extends GenericContainer { protected static $IMAGE = 'myapp:latest'; public function beforeStart(): void { $this->withName('myapp-test') ->withExposedPorts([3000, 5432]) ->withEnvs([ 'DATABASE_URL' => 'postgresql://user:password@db:5432/testdb', 'LOG_LEVEL' => 'debug' ]) ->withLabels([ 'environment' => 'test', 'team' => 'backend' ]) ->withFileSystemBind( '/host/logs', '/app/logs', BindMode::READ_WRITE() ) ->withWorkingDirectory('/app') ->withStartupTimeout(60) ->withAutoRemoveOnExit(true) ->withReuseMode(ReuseMode::RESTART()) ->withImagePullPolicy(ImagePullPolicy::MISSING()) ->withStartupCheckStrategy( (new IsRunningStartupCheckStrategy()) ->withTimeout(30) ) ->withWaitStrategy( (new LogMessageWaitStrategy()) ->withPattern('Server listening on port 3000') ->withTimeoutSeconds(45) ); } } $instance = Testcontainers::run(AppContainer::class); ``` -------------------------------- ### Quick Start: Running a Docker Container for Tests Source: https://github.com/k-kinzal/testcontainers-php/blob/main/README.md This example demonstrates how to start a Docker container using testcontainers-php and use it within a PHPUnit test. Containers are automatically stopped when the test concludes. ```php withExposedPorts([3306]) ->withEnv('MYSQL_ROOT_PASSWORD', 'secret') ->withEnv('MYSQL_DATABASE', 'testdb'); } } $instance = Testcontainers::run(MySQLContainer::class); // Get connection information $host = $instance->getHost(); $port = $instance->getMappedPort(3306); $dsn = "mysql:host=$host;port=$port;dbname=testdb"; // Check labels $sessionId = $instance->getLabel('org.testcontainers.session-id'); // Check state if ($instance->isRunning()) { $pdo = new PDO($dsn, 'root', 'secret'); } // Cleanup $instance->stop(); ``` -------------------------------- ### Start and Stop Containers Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/QUICK-REFERENCE.md Learn how to start a new container instance, stop all running containers, or stop a specific container instance. ```php // Start a container $instance = Testcontainers::run(MyContainer::class); ``` ```php // Stop all containers Testcontainers::stop(); ``` ```php // Stop one container $instance->stop(); ``` -------------------------------- ### Quick Start with GenericContainer Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/INDEX.md Demonstrates the basic usage of Testcontainers-PHP to run a MySQL container, expose its port, and set environment variables. Use this for a quick setup of common services. ```php use Testcontainers\Testcontainers; use Testcontainers\Containers\GenericContainer\GenericContainer; class MySQLContainer extends GenericContainer { protected static $IMAGE = 'mysql:8'; public function beforeStart(): void { $this->withExposedPorts([3306]) ->withEnv('MYSQL_ROOT_PASSWORD', 'secret'); } } $instance = Testcontainers::run(MySQLContainer::class); $port = $instance->getMappedPort(3306); $host = $instance->getHost(); // Use container... Testcontainers::stop(); ``` -------------------------------- ### Start and Use GenericContainer Instance Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/generic-container.md Initiate the container startup process using the `start()` method. This method returns a `GenericContainerInstance` object, which provides access to the container's host and mapped ports. ```php $container = new GenericContainer('mysql:8'); $instance = $container->start(); echo $instance->getHost(); // Container host echo $instance->getMappedPort(3306); // Mapped port ``` -------------------------------- ### start Method Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/generic-container.md Starts the Docker container based on the configured settings. This process includes validation, port allocation, executing the 'docker run' command, and running startup checks. ```APIDOC ## Method `start` ### Description Starts the Docker container. This method orchestrates the container startup process, including configuration validation, port allocation, Docker command execution, and startup checks. ### Returns `GenericContainerInstance` — An instance representing the running container, providing access to its host and mapped ports. ### Example ```php $container = new GenericContainer('mysql:8'); $instance = $container->start(); echo $instance->getHost(); // Container host echo $instance->getMappedPort(3306); // Mapped port ``` ``` -------------------------------- ### Complete GenericContainer Example with Lifecycle Hooks Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/generic-container.md This example demonstrates a custom `ApplicationContainer` extending `GenericContainer`, utilizing `beforeStart()` for extensive configuration and `afterStart()` for logging. It also includes a `DatabaseTest` class showing how to run the application container alongside a database container. ```php use Testcontainers\Testcontainers; use Testcontainers\Containers\GenericContainer\GenericContainer; use Testcontainers\Containers\Types\BindMode; use Testcontainers\Containers\StartupCheckStrategy\IsRunningStartupCheckStrategy; use Testcontainers\Containers\WaitStrategy\LogMessageWaitStrategy; class ApplicationContainer extends GenericContainer { protected static $IMAGE = 'myapp:latest'; private $databaseInstance; public function withDatabase($dbInstance): self { $this->databaseInstance = $dbInstance; return $this; } public function beforeStart(): void { // Basic configuration $this->withName('myapp-test') ->withExposedPorts([3000, 8080]) ->withWorkingDirectory('/app') // Environment ->withEnvs([ 'NODE_ENV' => 'test', 'LOG_LEVEL' => 'debug', 'DATABASE_HOST' => $this->databaseInstance->getHost(), 'DATABASE_PORT' => (string) $this->databaseInstance->getMappedPort(5432), ]) // File system ->withFileSystemBind( getcwd() . '/logs', '/app/logs', BindMode::READ_WRITE() ) // Startup ->withStartupTimeout(60) ->withStartupCheckStrategy( new IsRunningStartupCheckStrategy() ) ->withWaitStrategy( (new LogMessageWaitStrategy()) ->withPattern('Server listening on port 3000') ->withTimeoutSeconds(45) ); } public function afterStart($instance): void { // Wait for readiness beyond just "listening" echo "Application started at http://{$instance->getHost()}:3000"; } } // Usage class DatabaseTest extends \PHPUnit\Framework\TestCase { private $dbInstance; private $appInstance; public function setUp(): void { // Start database first $dbContainer = new GenericContainer('postgres:15'); $dbContainer->withEnvs([ 'POSTGRES_PASSWORD' => 'secret', 'POSTGRES_DB' => 'testdb' ]) ->withExposedPorts([5432]); $this->dbInstance = Testcontainers::run($dbContainer); // Start application with database $appContainer = new ApplicationContainer(); $appContainer->withDatabase($this->dbInstance); $this->appInstance = Testcontainers::run($appContainer); } public function testApplicationHealth(): void { $host = $this->appInstance->getHost(); $port = $this->appInstance->getMappedPort(3000); $response = @file_get_contents("http://$host:$port/health"); $this->assertNotFalse($response); } public function tearDown(): void { Testcontainers::stop(); } } ``` -------------------------------- ### HttpWaitStrategy Example Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/wait-strategies.md Example demonstrating how to use `HttpWaitStrategy` within a custom container class to configure the readiness check for an Nginx server. ```APIDOC ### Example ```php use Testcontainers estcontainers; use Testcontainers\Containers\GenericContainer\GenericContainer; use Testcontainers\Containers\WaitStrategy\HttpWaitStrategy; class WebServerContainer extends GenericContainer { protected static $IMAGE = 'nginx:latest'; public function beforeStart(): void { $this->withExposedPorts([80]) ->withWaitStrategy( (new HttpWaitStrategy()) ->withPath('/health') ->withExpectedResponseCode(200) ->withTimeoutSeconds(60) ); } } $instance = Testcontainers::run(WebServerContainer::class); ``` ``` -------------------------------- ### Example: Fluent API for Name and Commands Source: https://github.com/k-kinzal/testcontainers-php/blob/main/docs/container-configuration.md Demonstrates configuring a container's name and commands using the fluent API. ```php $container = (new GenericContainer('nginx:latest')) ->withName('my-nginx-container') ->withCommands(['nginx', '-g', 'daemon off;']); ``` -------------------------------- ### Implementing a Custom Port Strategy Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/port-strategies.md Create a custom port strategy by implementing the `PortStrategy` interface. This example shows a strategy that generates sequential ports starting from 10000 and retries on conflict. ```php use Testcontainers\Containers\PortStrategy\PortStrategy; use Testcontainers\Containers\PortStrategy\ConflictBehavior; class CustomPortStrategy implements PortStrategy { private $basePort = 10000; private $index = 0; public function getPort(): int { return $this->basePort + ($this->index++); } public function conflictBehavior(): ConflictBehavior { return ConflictBehavior::RETRY(); } } // Usage $container->withPortStrategy(new CustomPortStrategy()); ``` -------------------------------- ### Starting Containers Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/INDEX.md Methods for initiating and managing the lifecycle of Docker containers. ```APIDOC ## `Testcontainers::run()` ### Description Starts a Docker container and returns a `Container` instance. ### Method `Testcontainers::run(GenericContainer $container)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $container = Testcontainers::run(new GenericContainer('alpine')); ``` ### Response #### Success Response (200) - **Container** (object) - An instance of the running container. #### Response Example ```php // Example of a Container object ``` ## `Container::start()` ### Description Starts a container and returns an instance of the container. ### Method `Container::start()` ### Parameters None ### Request Example ```php $container = new GenericContainer('alpine'); $container->start(); ``` ### Response #### Success Response (200) - **Container** (object) - The started container instance. #### Response Example ```php // Example of a Container object ``` ## `GenericContainer::__construct()` ### Description Initializes a new `GenericContainer` instance, preparing it for configuration and startup. ### Method `GenericContainer::__construct(string $image = 'alpine', array $command = [])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $container = new GenericContainer('nginx:latest'); ``` ### Response #### Success Response (200) - **GenericContainer** (object) - A new instance of GenericContainer. #### Response Example ```php // Example of a GenericContainer object ``` ``` -------------------------------- ### withStartupTimeout Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/container.md Sets the maximum time to wait for the container to start up. If the container does not start within this duration, an error may be thrown. ```APIDOC ## withStartupTimeout($timeout) ### Description Sets the maximum time to wait for container startup. ### Method ```php public function withStartupTimeout(int $timeout): self ``` ### Parameters #### Path Parameters - **timeout** (int) - Required - Timeout in seconds ``` -------------------------------- ### ReuseMode Constructor and Usage Example Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/types.md Demonstrates how to instantiate ReuseMode using its constructor and provides an example of using the withReuseMode method. ```APIDOC ## ReuseMode::__construct() ### Description Initializes a new ReuseMode instance with a specified mode. ### Method `public function __construct(string $mode)` ### Parameters #### Path Parameters - **mode** (string) - Required - One of: 'add', 'restart', 'reuse' ### Example ```php use Testcontainers\Containers\ReuseMode; $container->withReuseMode(ReuseMode::REUSE()); ``` ``` -------------------------------- ### Verifying Startup Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/INDEX.md Strategies to check if a container has successfully started and is operational. ```APIDOC ## Startup Check Strategies ### Description Strategies to verify that a container has started correctly. ### Strategies - `IsRunningStartupCheckStrategy`: Checks if the container process is running. - `OneShotStartupCheckStrategy`: Executes a command within the container and checks its exit code. ### Example Usage ```php $container = new GenericContainer('alpine') ->withStartupCheckStrategy(new OneShotStartupCheckStrategy(['echo', 'hello'])); Testcontainers::run($container); ``` ``` -------------------------------- ### Start Container Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/container.md Initiates the container startup process and returns an instance of the running container. May throw exceptions on failure. ```php public function start(): ContainerInstance ``` -------------------------------- ### Implement beforeStart() for Container Configuration Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/generic-container.md Use the `beforeStart()` method to configure container settings before it is started. This is useful for setting environment variables or other configurations that should be applied just before the container launches. ```php public function beforeStart(): void { // Configure container here $this->withEnv('APP_MODE', 'test'); } ``` -------------------------------- ### Multi-Stage Container Setup with Ports, Labels, and Envs Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/generic-container.md Configure a container with multiple exposed ports, labels, and environment variables for complex application setups. This is useful for backend services that depend on databases or caches. ```php class ComplexContainer extends GenericContainer { protected static $IMAGE = 'complex:latest'; public function beforeStart(): void { $this->withExposedPorts([3000, 5432, 6379]) ->withLabels([ 'tier' => 'backend', 'environment' => 'test' ]) ->withEnvs([ 'DATABASE_URL' => 'postgresql://user:pass@localhost:5432/db', 'REDIS_URL' => 'redis://localhost:6379' ]); } } $instance = Testcontainers::run(ComplexContainer::class); $appPort = $instance->getMappedPort(3000); $dbPort = $instance->getMappedPort(5432); $redisPort = $instance->getMappedPort(6379); ``` -------------------------------- ### Starting and Stopping Containers Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/00-START-HERE.md Provides methods to start new containers and stop all running containers managed by Testcontainers. ```APIDOC ## Starting and Stopping Containers ### Description Methods for managing the lifecycle of containers. ### Methods #### `Testcontainers::run(string $className, array $options = [])` Starts a new container based on the provided class name or instance. #### `Testcontainers::stop()` Stops all containers that have been started by Testcontainers. ### Usage Examples ```php // Start a container $instance = Testcontainers::run(MyContainer::class); // Stop all containers Testcontainers::stop(); ``` ``` -------------------------------- ### Create a Bind Mount Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/types.md Example of creating a bind mount for a container, specifying source, target, and read-only status. ```php use Testcontainers\Containers\Types\Mount; use Testcontainers\Containers\Types\BindMode; $mount = new Mount(); $mount->type = 'bind'; $mount->source = '/host/data'; $mount->target = '/container/data'; $mount->readOnly = BindMode::READ_ONLY()->isReadOnly(); ``` -------------------------------- ### Example: Static Properties for Image, Name, and Commands Source: https://github.com/k-kinzal/testcontainers-php/blob/main/docs/container-configuration.md Demonstrates setting the Docker image, container name, and command using static properties within a container class. ```php class MyContainer extends GenericContainer { protected static $IMAGE = 'nginx:latest'; protected static $NAME = 'my-nginx-container'; protected static $COMMANDS = ['nginx', '-g', 'daemon off;']; } ``` -------------------------------- ### Start and Configure PostgreSQL Container for Testing Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/QUICK-REFERENCE.md Defines a custom PostgreSQL container and demonstrates how to run it and connect using PDO. Ensure the 'postgres:15' image is available. ```php class PostgreSQLContainer extends GenericContainer { protected static $IMAGE = 'postgres:15'; public function beforeStart(): void { $this->withExposedPorts([5432]) ->withEnvs([ 'POSTGRES_PASSWORD' => 'secret', 'POSTGRES_DB' => 'testdb' ]); } } $db = Testcontainers::run(PostgreSQLContainer::class); $pdo = new PDO( "pgsql:host={$db->getHost()};port={$db->getMappedPort(5432)}", 'postgres', 'secret' ); ``` -------------------------------- ### Example: Mounting a Read-Only File System Bind Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/types.md Demonstrates how to mount a host directory to a container directory with read-only access using BindMode::READ_ONLY(). ```php use Testcontainers\Containers\Types\BindMode; $container->withFileSystemBind( '/host/data', '/container/data', BindMode::READ_ONLY() ); ``` -------------------------------- ### Testcontainers::run() Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/testcontainers.md Starts a container instance and registers it for automatic cleanup. It can instantiate the container class if provided as a string, checks reuse mode, calls lifecycle hooks, starts the container, and ensures cleanup. ```APIDOC ## Testcontainers::run() ### Description Starts a container instance and registers it for automatic cleanup. ### Method `public static function run($containerClass): ContainerInstance` ### Parameters #### Path Parameters - **containerClass** (class-string\|Container) - Required - The class name or instance of a container to run. Must extend or implement `Container`. ### Returns `ContainerInstance` - The started container instance. ### Throws - `LogicException` - If the container class is invalid or not an instance of `Container` ### Behavior - Instantiates the container class if provided as a string - Checks reuse mode; reuses existing running container if mode is `REUSE` - Stops and restarts container if mode is `RESTART` - Calls `beforeStart()` hook if defined on the container class - Starts the container - Calls `afterStart($instance)` hook if defined on the container class - Executes container cleanup once per process (removes all testcontainers label) ### Request Example ```php use Testcontainers\Testcontainers; use Testcontainers\Containers\GenericContainer\GenericContainer; class MyContainer extends GenericContainer { protected static $IMAGE = 'alpine:latest'; } // Start by class name $instance = Testcontainers::run(MyContainer::class); // Or start by instance $container = new MyContainer(); $instance = Testcontainers::run($container); // Access container information $containerId = $instance->getContainerId(); $host = $instance->getHost(); $port = $instance->getMappedPort(3306); ``` ``` -------------------------------- ### beforeStart() Hook Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/generic-container.md The `beforeStart()` method is called before the container is started. It's ideal for performing initial configurations, such as setting environment variables or defining port mappings. ```APIDOC ## beforeStart() ### Description Called before the container is started. Allows for custom configuration logic. ### Method Signature `public function beforeStart(): void` ### Example Usage ```php public function beforeStart(): void { // Configure container here $this->withEnv('APP_MODE', 'test'); } ``` ### Use Case Defer configuration until the container is about to be started. ``` -------------------------------- ### Example Usage of OneShotStartupCheckStrategy Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/startup-check-strategies.md Demonstrates how to use the OneShotStartupCheckStrategy within a custom container definition. This example configures a migration container to use the strategy with a specific timeout and retry interval. ```php use Testcontainers\Containers\StartupCheckStrategy\OneShotStartupCheckStrategy; class MigrationContainer extends GenericContainer { protected static $IMAGE = 'myapp:migrations'; public function beforeStart(): void { $this->withStartupCheckStrategy( (new OneShotStartupCheckStrategy()) ->withTimeout(60) ->withRetryInterval(100000) ); } } $instance = Testcontainers::run(MigrationContainer::class); // At this point, the migration has completed with exit code 0 ``` -------------------------------- ### Example: Method Overrides for Image, Name, and Commands Source: https://github.com/k-kinzal/testcontainers-php/blob/main/docs/container-configuration.md Demonstrates overriding methods to set the Docker image, container name, and command. ```php class MyContainer extends GenericContainer { protected function image() { return 'nginx:latest'; } protected function name() { return 'my-nginx-container'; } protected function commands() { return ['nginx', '-g', 'daemon off;']; } } ``` -------------------------------- ### Start and Stop Containers with Testcontainers PHP Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/00-START-HERE.md Use `Testcontainers::run()` to start a container by its class name or instance. Call `Testcontainers::stop()` to stop all currently running containers. ```php // In: class name or instance // Out: running ContainerInstance $instance = Testcontainers::run(MyContainer::class); // Stop all started containers Testcontainers::stop(); ``` -------------------------------- ### Create and Configure Docker Client Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/docker-client.md Instantiate a Docker client and configure its timeout and logger. This is the starting point for most Docker client operations. ```php use Testcontainers\Docker\DockerClientFactory; $client = DockerClientFactory::create(); // Configure the client $configuredClient = $client ->withTimeout(60) ->withLogger($logger); ``` -------------------------------- ### Run a Docker Container Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/docker-client.md Execute a command within a new Docker container. This example runs 'echo hello world' in an Ubuntu container and detaches it. ```php $output = $client->run( 'ubuntu:latest', 'echo', ['hello world'], ['detach' => true] ); // Returns DockerRunOutput ``` -------------------------------- ### Example Usage of ReuseMode Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/types.md Demonstrates how to set the container reuse mode to REUSE using the factory method. ```php use Testcontainers\Containers\ReuseMode; $container->withReuseMode(ReuseMode::REUSE()); ``` -------------------------------- ### Start/Stop Containers Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates how to start a new container, stop all running containers managed by Testcontainers, or stop a specific container instance. ```APIDOC ## Start/Stop Containers ### Start a container ```php // Start a container $instance = Testcontainers::run(MyContainer::class); ``` ### Stop all containers ```php // Stop all containers Testcontainers::stop(); ``` ### Stop one container ```php // Stop one container $instance->stop(); ``` ``` -------------------------------- ### Example Usage of Environments Class - PHP Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/types.md Demonstrates how to retrieve Docker host and SSH forwarding configurations using the Environments class. Checks if SSH port forwarding is enabled. ```php use Testcontainers\Environments; $dockerHost = Environments::DOCKER_HOST(); $sshConfig = Environments::TESTCONTAINERS_SSH_FEEDFORWARDING(); if ($sshConfig) { // SSH port forwarding is enabled } ``` -------------------------------- ### Run a Container Instance Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/testcontainers.md Use `Testcontainers::run()` to start a container and register it for automatic cleanup. You can provide either the class name or an instance of a container. ```php use Testcontainers\Testcontainers; use Testcontainers\Containers\GenericContainer\GenericContainer; class MyContainer extends GenericContainer { protected static $IMAGE = 'alpine:latest'; } // Start by class name $instance = Testcontainers::run(MyContainer::class); // Or start by instance $container = new MyContainer(); $instance = Testcontainers::run($container); // Access container information $containerId = $instance->getContainerId(); $host = $instance->getHost(); $port = $instance->getMappedPort(3306); ``` -------------------------------- ### Configure RESTART Reuse Mode Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/configuration.md Configure the container to stop any existing instance and start a new one. ```php $container->withReuseMode(ReuseMode::RESTART()); ``` -------------------------------- ### Implement `beforeStart` Hook Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/testcontainers.md Define the `beforeStart()` method within your container class to execute custom logic before the container is started. This is useful for setting environment variables or other configurations. ```php class MyContainer extends GenericContainer { protected static $IMAGE = 'postgres:13'; public function beforeStart(): void { $this->withEnv('POSTGRES_PASSWORD', 'test'); } } ``` -------------------------------- ### afterStart() Hook Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/generic-container.md The `afterStart()` method is invoked after the container has successfully started. Use this hook to perform post-startup tasks like running database migrations or seeding data. ```APIDOC ## afterStart(ContainerInstance $instance) ### Description Called after the container has successfully started. Useful for initializing container state. ### Method Signature `public function afterStart(ContainerInstance $instance): void` ### Parameters #### Path Parameters - **instance** (ContainerInstance) - Required - The running container instance. ### Example Usage ```php public function afterStart(ContainerInstance $instance): void { // Initialize container state here $port = $instance->getMappedPort(3000); // Set up database, run migrations, etc. } ``` ### Use Case Perform initialization after the container is ready (e.g., database migrations, seeding). ``` -------------------------------- ### Handle StartupCheckFailedException Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/startup-check-strategies.md Catch and handle the StartupCheckFailedException when a container fails to start according to its configured strategy. This exception provides the reason for the failure. ```php try { $instance = Testcontainers::run(MyContainer::class); } catch (StartupCheckFailedException $e) { echo "Container failed to start: " . $e->getMessage(); } ``` -------------------------------- ### Set Container Startup Timeout Source: https://github.com/k-kinzal/testcontainers-php/blob/main/docs/container-configuration.md Configure the maximum time to wait for a container to start before throwing an exception. Adjust this for containers with longer initialization periods. ```php class MyContainer extends GenericContainer { protected static $STARTUP_TIMEOUT = 120; // Example: 120 seconds } ``` ```php class MyContainer extends GenericContainer { protected function startupTimeout() { return 120; } } ``` ```php $container = (new GenericContainer('nginx:latest')) ->withStartupTimeout(120); ``` -------------------------------- ### Set Container Command Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/container.md Configure the command to be executed when the container starts using `withCommand`. This accepts a single string. ```php public function withCommand(string $cmd): self ``` -------------------------------- ### GitHub Actions CI Setup Source: https://github.com/k-kinzal/testcontainers-php/blob/main/docs/ci-setup.md Configure GitHub Actions to run tests with testcontainers-php. Assumes Docker is pre-installed on runners. ```yaml name: Tests on: push: branches: [ main ] pull_request: branches: [ main ] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: '8.1' extensions: pdo, pdo_mysql - name: Install dependencies run: composer install --prefer-dist --no-progress - name: Run tests run: vendor/bin/phpunit ``` -------------------------------- ### withStartupCheckStrategy Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/container.md Sets the strategy for checking if the container has started successfully. This allows customization of how the system determines container readiness. ```APIDOC ## withStartupCheckStrategy($strategy) ### Description Sets the strategy for checking container startup status. ### Method ```php public function withStartupCheckStrategy(StartupCheckStrategy $strategy): self ``` ### Parameters #### Path Parameters - **strategy** (StartupCheckStrategy) - Required - Startup check strategy implementation ``` -------------------------------- ### Implement `afterStart` Hook Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/testcontainers.md Implement the `afterStart()` method in your container class to run code after the container has successfully started. This hook receives the `ContainerInstance` and can be used for post-startup initialization. ```php class MyContainer extends GenericContainer { protected static $IMAGE = 'mysql:8'; public function afterStart(ContainerInstance $instance): void { // Perform initialization after container is ready $host = $instance->getHost(); $port = $instance->getMappedPort(3306); } } ``` -------------------------------- ### Configure ADD Reuse Mode Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/configuration.md Configure the container to always start a new instance, even if an existing one is available. This is the default behavior. ```php use Testcontainers\Containers\ReuseMode; $container->withReuseMode(ReuseMode::ADD()); ``` -------------------------------- ### CircleCI Machine Executor CI Setup Source: https://github.com/k-kinzal/testcontainers-php/blob/main/docs/ci-setup.md Set up CircleCI using the Machine Executor for seamless testcontainers-php integration. Docker is pre-installed on the Ubuntu VM. ```yaml version: 2.1 jobs: test: machine: image: ubuntu-2204:current steps: - checkout - run: name: Install PHP and Composer command: | sudo apt-get update sudo apt-get install -y php php-cli php-curl php-mbstring php-xml php-zip php-pdo php-mysql php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" php composer-setup.php --install-dir=/usr/local/bin --filename=composer php -r "unlink('composer-setup.php');" - run: name: Install dependencies command: composer install --prefer-dist --no-progress - run: name: Run tests command: vendor/bin/phpunit workflows: version: 2 test: jobs: - test ``` -------------------------------- ### Remote Docker Host with SSH Port Forwarding Example Source: https://github.com/k-kinzal/testcontainers-php/blob/main/docs/environments.md Connect to a remote Docker daemon and enable SSH port forwarding to access container ports from a machine without Docker installed. Ensure TESTCONTAINERS_HOST_OVERRIDE is set for correct host resolution. ```php putenv('DOCKER_HOST=tcp://remote-docker:2375'); putenv('TESTCONTAINERS_SSH_FEEDFORWARDING=user@remote-docker:22'); putenv('TESTCONTAINERS_HOST_OVERRIDE=localhost'); $container = (new GenericContainer('nginx:latest')) ->withExposedPorts(80); ``` -------------------------------- ### ImagePullPolicy Usage Example Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/types.md Example demonstrating how to use the ImagePullPolicy constants with the `withImagePullPolicy` method. ```APIDOC ### Example ```php use Testcontainers\Containers\Types\ImagePullPolicy; $container->withImagePullPolicy(ImagePullPolicy::ALWAYS()); ``` ``` -------------------------------- ### Implement afterStart() for Post-Start Initialization Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/generic-container.md The `afterStart()` method is called after the container has successfully started. Use this to perform initialization tasks that depend on the container being fully operational, such as setting up databases or running migrations. ```php public function afterStart(ContainerInstance $instance): void { // Initialize container state here $port = $instance->getMappedPort(3306); // Set up database, run migrations, etc. } ``` -------------------------------- ### Multi-Service Setup with Interdependent Containers Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates setting up multiple services (PostgreSQL, Redis, API) in Testcontainers, configuring their dependencies via environment variables, and then stopping all containers. Ensure 'postgres:15', 'redis:7', and 'myapi:latest' images are available. ```php $db = Testcontainers::run(new GenericContainer('postgres:15') ->withExposedPorts([5432])); $cache = Testcontainers::run(new GenericContainer('redis:7') ->withExposedPorts([6379])); $api = Testcontainers::run(new GenericContainer('myapi:latest') ->withExposedPorts([8080]) ->withEnv('DATABASE_URL', "postgresql://user@{$db->getHost()}:{$db->getMappedPort(5432)}/db") ->withEnv('REDIS_URL', "redis://{$cache->getHost()}:{$cache->getMappedPort(6379)}")); // Run tests... Testcontainers::stop(); ``` -------------------------------- ### Testcontainers::stop() Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/testcontainers.md Stops all started containers and removes them from the internal registry. It iterates through all started container instances, calls `stop()` on each, and removes successfully stopped instances. ```APIDOC ## Testcontainers::stop() ### Description Stops all started containers and removes them from the internal registry. ### Method `public static function stop(): void` ### Behavior - Iterates through all started container instances - Calls `stop()` on each instance - Removes successfully stopped instances from the registry - Aggregates errors from failed stop attempts ### Throws - `Testcontainers\Exceptions\ContainerStopException` - If any containers fail to stop. Contains all errors via `getErrors()`. ### Request Example ```php use Testcontainers\Testcontainers; try { Testcontainers::stop(); } catch (Testcontainers\Exceptions\ContainerStopException $e) { foreach ($e->getErrors() as $key => $error) { echo "Failed to stop container {$key}: {$error->getMessage()}"; } } ``` ``` -------------------------------- ### PHP HttpWaitStrategy Example: Nginx Container Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/api-reference/wait-strategies.md Demonstrates how to configure an HttpWaitStrategy for an Nginx container. This example sets a specific health check path, expected response code, and timeout. ```php use Testcontainers\Testcontainers; use Testcontainers\Containers\GenericContainer\GenericContainer; use Testcontainers\Containers\WaitStrategy\HttpWaitStrategy; class WebServerContainer extends GenericContainer { protected static $IMAGE = 'nginx:latest'; public function beforeStart(): void { $this->withExposedPorts([80]) ->withWaitStrategy( (new HttpWaitStrategy()) ->withPath('/health') ->withExpectedResponseCode(200) ->withTimeoutSeconds(60) ); } } $instance = Testcontainers::run(WebServerContainer::class); ``` -------------------------------- ### ReuseMode Factory Methods Source: https://github.com/k-kinzal/testcontainers-php/blob/main/_autodocs/types.md Factory methods to create instances of ReuseMode with specific behaviors: ADD (always start new), RESTART (stop and start new), and REUSE (reuse existing). ```APIDOC ## ReuseMode::ADD() ### Description Creates a ReuseMode with ADD behavior, which always starts a new container. ### Method `public static function ADD(): self` ### Returns `ReuseMode` — New instance with ADD mode. ## ReuseMode::RESTART() ### Description Creates a ReuseMode with RESTART behavior, which stops an existing container and starts a new one. ### Method `public static function RESTART(): self` ### Returns `ReuseMode` — New instance with RESTART mode. ## ReuseMode::REUSE() ### Description Creates a ReuseMode with REUSE behavior, which reuses an existing running container. ### Method `public static function REUSE(): self` ### Returns `ReuseMode` — New instance with REUSE mode. ```