Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ review: ## Run static code analysis

.PHONY: show-reports
show-reports: ## Open static analysis reports (e.g., coverage, lints) in the browser
@sensible-browser report/coverage/coverage-html/index.html report/coverage/mutation-report.html
@sensible-browser report/coverage/coverage-html/index.html

.PHONY: clean
clean: ## Remove dependencies and generated artifacts
Expand Down
51 changes: 26 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ composer require tiny-blocks/docker-container
### Creating a container

Creates a container from a specified image and optionally a name.
The `from` method can be used to initialize a new container instance with an image and an optional name for
identification.
The `from` method initializes a new container instance with an image and an optional name for identification.

```php
$container = GenericDockerContainer::from(image: 'php:8.3-fpm', name: 'my-container');
Expand Down Expand Up @@ -78,19 +77,11 @@ $container->run(commands: ['ls', '-la'], waitAfterStarted: ContainerWaitForTime:
### Running a container if it doesn't exist

The `runIfNotExists` method starts a container only if it doesn't already exist.
Optionally, it allows you to execute commands within the container after it has started and define a condition to wait
for using a `ContainerWaitAfterStarted` instance.

```php
$container->runIfNotExists();
```

**Example with commands only:**

```php
$container->runIfNotExists(commands: ['ls', '-la']);
```

**Example with commands and a wait condition:**

```php
Expand All @@ -99,26 +90,24 @@ $container->runIfNotExists(commands: ['ls', '-la'], waitAfterStarted: ContainerW

### Setting network

The `withNetwork` method connects the container to a specified Docker network by name, allowing you to define the
network configuration the container will use.
The `withNetwork` method connects the container to a specified Docker network by name.

```php
$container->withNetwork(name: 'my-network');
```

### Setting port mappings

Maps ports between the host and the container.
The `withPortMapping` method maps a port from the host to a port inside the container.
Maps ports between the host and the container. Multiple port mappings are supported.

```php
$container->withPortMapping(portOnHost: 9000, portOnContainer: 9000);
$container->withPortMapping(portOnHost: 8080, portOnContainer: 80);
```

### Setting volumes mappings

Maps a volume from the host to the container.
The `withVolumeMapping` method allows you to link a directory from the host to the container.

```php
$container->withVolumeMapping(pathOnHost: '/path/on/host', pathOnContainer: '/path/in/container');
Expand All @@ -127,7 +116,6 @@ $container->withVolumeMapping(pathOnHost: '/path/on/host', pathOnContainer: '/pa
### Setting environment variables

Sets environment variables inside the container.
The `withEnvironmentVariable` method allows you to configure environment variables within the container.

```php
$container->withEnvironmentVariable(key: 'XPTO', value: '123');
Expand All @@ -136,9 +124,6 @@ $container->withEnvironmentVariable(key: 'XPTO', value: '123');
### Disabling auto-remove

Prevents the container from being automatically removed when stopped.
By default, Docker removes containers after they stop.
The `withoutAutoRemove` method disables this feature, keeping the container around even after it finishes its
execution.

```php
$container->withoutAutoRemove();
Expand All @@ -147,7 +132,6 @@ $container->withoutAutoRemove();
### Copying files to a container

Copies files or directories from the host machine to the container.
The `copyToContainer` method allows you to transfer files from the host system into the container’s file system.

```php
$container->copyToContainer(pathOnHost: '/path/to/files', pathOnContainer: '/path/in/container');
Expand All @@ -156,10 +140,26 @@ $container->copyToContainer(pathOnHost: '/path/to/files', pathOnContainer: '/pat
### Waiting for a condition

The `withWaitBeforeRun` method allows the container to pause its execution until a specified condition is met before
starting.
starting. A timeout prevents the wait from blocking indefinitely.

```php
$container->withWaitBeforeRun(
wait: ContainerWaitForDependency::untilReady(
condition: MySQLReady::from(container: $container),
timeoutInSeconds: 30
)
);
```

### Setting readiness timeout for MySQL

The `withReadinessTimeout` method configures how long the MySQL container will wait for the database to become ready
before throwing a `ContainerWaitTimeout` exception. The default timeout is 30 seconds.

```php
$container->withWaitBeforeRun(wait: ContainerWaitForDependency::untilReady(condition: MySQLReady::from(container: $container)));
$container = MySQLDockerContainer::from(image: 'mysql:8.1', name: 'my-database')
->withReadinessTimeout(timeoutInSeconds: 60)
->run();
```

<div id='usage-examples'></div>
Expand Down Expand Up @@ -199,7 +199,7 @@ The following commands are used to prepare the environment:
-v ${PWD}:/app \
-v ${PWD}/tests/Integration/Database/Migrations:/test-adm-migrations \
-v /var/run/docker.sock:/var/run/docker.sock \
-w /app gustavofreze/php:8.3 bash -c "composer tests"
-w /app gustavofreze/php:8.5-alpine bash -c "composer tests"
```

The MySQL container is configured and started:
Expand All @@ -214,7 +214,7 @@ $mySQLContainer = MySQLDockerContainer::from(image: 'mysql:8.1', name: 'test-dat
->withPortMapping(portOnHost: 3306, portOnContainer: 3306)
->withRootPassword(rootPassword: 'root')
->withGrantedHosts()
->withVolumeMapping(pathOnHost: '/var/lib/mysql', pathOnContainer: '/var/lib/mysql')
->withReadinessTimeout(timeoutInSeconds: 60)
->withoutAutoRemove()
->runIfNotExists();
```
Expand All @@ -240,7 +240,8 @@ $flywayContainer = GenericDockerContainer::from(image: 'flyway/flyway:11.0.0')
wait: ContainerWaitForDependency::untilReady(
condition: MySQLReady::from(
container: $mySQLContainer
)
),
timeoutInSeconds: 30
)
)
->withEnvironmentVariable(key: 'FLYWAY_URL', value: $jdbcUrl)
Expand Down
3 changes: 1 addition & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@
"php": "^8.5",
"symfony/process": "^7.4",
"tiny-blocks/ksuid": "^1.5",
"tiny-blocks/mapper": "^2.0",
"tiny-blocks/collection": "^1.15"
"tiny-blocks/collection": "^2.0"
},
"require-dev": {
"ext-pdo": "*",
Expand Down
19 changes: 5 additions & 14 deletions src/Contracts/Address.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,26 @@
namespace TinyBlocks\DockerContainer\Contracts;

/**
* Defines the network configuration of a running Docker container.
* Represents the network address of a running Docker container.
*/
interface Address
{
/**
* Returns the IP address of the running container.
*
* The IP address is available for containers running in the following network modes:
* - `BRIDGE`: IP address is assigned and accessible within the bridge network.
* - `IPVLAN`: IP address is assigned and accessible within the ipvlan network.
* - `OVERLAY`: IP address is assigned and accessible within an overlay network.
* - `MACVLAN`: IP address is assigned and accessible within a macvlan network.
*
* For containers running in the `HOST` network mode:
* - The IP address is `127.0.0.1` (localhost) on the host machine.
* Returns the IP address assigned to the container.
*
* @return string The container's IP address.
*/
public function getIp(): string;

/**
* Returns the network ports configuration for the running container.
* Returns the port mappings exposed by the container.
*
* @return Ports The container's network ports.
* @return Ports The container's exposed ports.
*/
public function getPorts(): Ports;

/**
* Returns the hostname of the running container.
* Returns the hostname of the container.
*
* @return string The container's hostname.
*/
Expand Down
26 changes: 14 additions & 12 deletions src/Contracts/ContainerStarted.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,54 +7,56 @@
use TinyBlocks\DockerContainer\Internal\Exceptions\DockerCommandExecutionFailed;

/**
* Defines the operations available for a Docker container that has been started.
* Represents a Docker container that has been started and is running.
*/
interface ContainerStarted
{
/**
* Default timeout in whole seconds used when stopping the container.
*/
public const int DEFAULT_TIMEOUT_IN_WHOLE_SECONDS = 300;

/**
* Returns the ID of the running container.
* Returns the unique identifier of the container.
*
* @return string The container's ID.
* @return string The container ID.
*/
public function getId(): string;

/**
* Returns the name of the running container.
* Returns the name assigned to the container.
*
* @return string The container's name.
* @return string The container name.
*/
public function getName(): string;

/**
* Returns the network address of the running container.
* Returns the network address of the container.
*
* @return Address The container's network address.
*/
public function getAddress(): Address;

/**
* Returns the environment variables of the running container.
* Returns the environment variables configured in the container.
*
* @return EnvironmentVariables The environment variables of the container.
* @return EnvironmentVariables The container's environment variables.
*/
public function getEnvironmentVariables(): EnvironmentVariables;

/**
* Stops the running container.
*
* @param int $timeoutInWholeSeconds The maximum time in seconds to wait for the container to stop.
* Default is {@see DEFAULT_TIMEOUT_IN_WHOLE_SECONDS} seconds.
* @return ExecutionCompleted The result of the stop command execution.
* @throws DockerCommandExecutionFailed If the stop command fails to execute.
* @throws DockerCommandExecutionFailed If the stop command fails.
*/
public function stop(int $timeoutInWholeSeconds = self::DEFAULT_TIMEOUT_IN_WHOLE_SECONDS): ExecutionCompleted;

/**
* Executes commands inside the running container after it has been started.
* Executes commands inside the running container.
*
* @param array $commands The commands to execute inside the container.
* @param array<int, string> $commands The commands to execute inside the container.
* @return ExecutionCompleted The result of the command execution.
* @throws DockerCommandExecutionFailed If the command execution fails.
*/
Expand Down
8 changes: 4 additions & 4 deletions src/Contracts/EnvironmentVariables.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@
namespace TinyBlocks\DockerContainer\Contracts;

/**
* Defines the environment variables configuration of a running Docker container.
* Represents the environment variables configured in a Docker container.
*/
interface EnvironmentVariables
{
/**
* Retrieves the value of an environment variable by its key.
* Returns the value of an environment variable by its key.
*
* @param string $key The key of the environment variable.
* @return string The value of the environment variable.
* @param string $key The name of the environment variable.
* @return string The value of the environment variable, or an empty string if not found.
*/
public function getValueBy(string $key): string;
}
10 changes: 5 additions & 5 deletions src/Contracts/ExecutionCompleted.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,21 @@
namespace TinyBlocks\DockerContainer\Contracts;

/**
* Represents the result of a completed command execution.
* Represents the result of a Docker command execution.
*/
interface ExecutionCompleted
{
/**
* Returns the output of the executed command.
* Returns the output produced by the executed command.
*
* @return string The command output.
* @return string The standard output on success, or the error output on failure.
*/
public function getOutput(): string;

/**
* Returns whether the command execution was successful.
* Indicates whether the command execution was successful.
*
* @return bool True if the command was successful, false otherwise.
* @return bool True if the execution was successful, false otherwise.
*/
public function isSuccessful(): bool;
}
16 changes: 7 additions & 9 deletions src/Contracts/MySQL/MySQLContainerStarted.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@
use TinyBlocks\DockerContainer\Contracts\ContainerStarted;

/**
* Extends the functionality of a started container to include MySQL-specific operations.
* Represents a MySQL Docker container that has been started and is running.
*/
interface MySQLContainerStarted extends ContainerStarted
{
/**
* Default JDBC options for connecting to the MySQL container.
* Default JDBC connection options for MySQL.
*
* @var array<string, string>
*/
public const array DEFAULT_JDBC_OPTIONS = [
'useSSL' => 'false',
Expand All @@ -22,14 +24,10 @@ interface MySQLContainerStarted extends ContainerStarted
];

/**
* Generates and returns a JDBC URL for connecting to the MySQL container.
*
* The URL is built using the container's hostname, port, and database name,
* with optional query parameters for additional configurations.
* Returns the JDBC connection URL for the MySQL container.
*
* @param array $options An array of key-value pairs to append to the JDBC URL.
* Defaults to {@see DEFAULT_JDBC_OPTIONS}.
* @return string The generated JDBC URL.
* @param array<string, string> $options JDBC connection options appended as query parameters.
* @return string The fully constructed JDBC URL.
*/
public function getJdbcUrl(array $options = self::DEFAULT_JDBC_OPTIONS): string;
}
11 changes: 5 additions & 6 deletions src/Contracts/Ports.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,21 @@
namespace TinyBlocks\DockerContainer\Contracts;

/**
* Defines the port's configuration of a Docker container.
* Represents the port mappings exposed by a Docker container.
*/
interface Ports
{
/**
* Returns an array of all exposed ports of the container.
* Returns all exposed ports mapped to the host.
*
* @return array An associative array where keys are the container's exposed ports
* and values are the corresponding ports on the host machine.
* @return array<int, int> The list of exposed port numbers.
*/
public function exposedPorts(): array;

/**
* Returns the first exposed port of the container.
* Returns the first exposed port, or null if no ports are exposed.
*
* @return int|null The first exposed port of the container, or null if no ports are exposed.
* @return int|null The first exposed port number, or null if none.
*/
public function firstExposedPort(): ?int;
}
Loading
Loading