Skip to content
Draft
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: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ We add additional stuff like:
* almost any PHP module preinstalled
* configuration based on ENV variables
* run multiple services (like php-fpm and nginx) with supervisord
* PHP-FPM that sizes itself to the container: at every start, the number of PHP-FPM workers follows the CPU and memory limits of the container (`cpus`, `mem_limit`), or the host without limits ([details](docs/environment-variables.md#size-of-the-php-fpm-pool))
* production defaults for larger applications: `opcache.max_accelerated_files` `32531`, and PHP-FPM replaces a worker after 1000 requests ([production](docs/images/php.md#production))

[![GitHub issues](https://img.shields.io/github/issues/webdevops/Dockerfile.svg)](https://github.com/webdevops/Dockerfile/issues)[![GitHub forks](https://img.shields.io/github/forks/webdevops/Dockerfile.svg)](https://github.com/webdevops/Dockerfile/network)[![GitHub stars](https://img.shields.io/github/stars/webdevops/Dockerfile.svg)](https://github.com/webdevops/Dockerfile/stargazers)[![GitHub license](https://img.shields.io/github/license/webdevops/Dockerfile.svg)](https://github.com/webdevops/Dockerfile/blob/master/LICENSE)
[![build](https://github.com/webdevops/Dockerfile/actions/workflows/build.yaml/badge.svg)](https://github.com/webdevops/Dockerfile/actions/workflows/build.yaml)
Expand Down
2 changes: 1 addition & 1 deletion ci/image-tests/Checks/PhpDevelopmentChecks.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public function testSettingsForDevelopment(): void
'opcache.revalidate_freq' => '0',
'opcache.validate_timestamps' => '1',
'opcache.interned_strings_buffer' => '16',
'opcache.max_accelerated_files' => '7963',
'opcache.max_accelerated_files' => '32531',
], $this->phpSettings([
'xdebug.mode', 'xdebug.start_with_request', 'opcache.memory_consumption', 'opcache.revalidate_freq',
'opcache.validate_timestamps', 'opcache.interned_strings_buffer', 'opcache.max_accelerated_files',
Expand Down
127 changes: 125 additions & 2 deletions ci/image-tests/Checks/PhpFpmEnvironmentChecks.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,28 @@

namespace Webdevops\Build\ImageTests\Checks;

use PHPUnit\Framework\Attributes\DataProvider;
use Webdevops\Build\ImageTests\Docker\Container;
use Webdevops\Build\ImageTests\ImageTestCase;

use function array_map;
use function ctype_digit;
use function escapeshellarg;
use function explode;
use function implode;
use function intdiv;
use function json_decode;
use function max;
use function microtime;
use function min;
use function preg_match;
use function preg_quote;
use function range;
use function sleep;
use function sprintf;
use function trim;
use function usleep;
use function vsprintf;

/**
* The PHP-FPM variables, see docs/environment-variables.md#php-fpm, and LOG_STDOUT and LOG_STDERR for PHP-FPM, see
Expand Down Expand Up @@ -67,7 +77,7 @@ public function testPhpFpmRequestTerminateTimeoutFromTheEnvironment(): void

/**
* FPM_PROCESS_MAX=2: with four slow requests at once, PHP-FPM runs no more than two workers, although the pool would
* allow five.
* allow more.
*/
public function testPhpFpmProcessMaxFromTheEnvironment(): void
{
Expand Down Expand Up @@ -160,7 +170,8 @@ public function testPhpFpmPoolDirectivesOfDockerConfFromTheEnvironment(): void
/**
* FPM_PM_START_SERVERS=3, FPM_PM_MIN_SPARE_SERVERS=3, FPM_PM_MAX_SPARE_SERVERS=4 and FPM_PM_MAX_CHILDREN=8, in a
* container of their own: three workers at the start, three idle ones besides three busy ones, eight at most
* under load, and four once the load is gone. The defaults would give 2, 4, 5 and 3.
* under load, and four once the load is gone. The values of the official image, with FPM_AUTO_SIZE=0, would give 2,
* 4, 5 and 3.
*/
public function testPhpFpmProcessManagerFromTheEnvironment(): void
{
Expand Down Expand Up @@ -209,6 +220,73 @@ public function testPhpFpmMaxRequestsAndIdleTimeoutFromTheEnvironment(): void
self::assertSame(0, $this->phpFpmWorkers($container), 'the idle worker exits after 5 s');
}

/**
* In the container of the class, which has no CPU or memory limit, the process manager is sized to the CPUs and the
* memory of the runner: pm.max_children is the smaller of the workers of 128 MB that fit into the memory beside
* OPcache (256 MB) and 256 MB for the other processes, and of four per CPU, at least two; the spare servers follow
* the CPUs, and pm.start_servers lies in between. The container log names the CPUs, the memory and the values. A
* worker ends after 1000 requests.
*/
public function testPhpFpmPoolIsSizedToTheContainer(): void
{
$container = self::container();
[$cpus, $memory] = $this->containerResources($container);
$children = max(2, min(intdiv($memory - 256 - 256, 128), 4 * $cpus));
$minSpare = max(1, min(intdiv($cpus, 2), $children));
$maxSpare = max($minSpare, min($children, 2 * $cpus));
$expected = [$children, $minSpare + intdiv($maxSpare - $minSpare, 2), $minSpare, $maxSpare];

$configuration = $this->assertCommandSucceeds('php-fpm -tt')->stderr;
self::assertSame($expected, self::phpFpmProcessManager($configuration), sprintf('%d CPUs, %d MB memory', $cpus, $memory));
self::assertMatchesRegularExpression('/NOTICE: \tpm\.max_requests = 1000$/m', $configuration);
self::assertMatchesRegularExpression(vsprintf(
'/^PHP-FPM: %d CPUs \([^)]+\), %d MB memory \([^)]+\) -> pm\.max_children=%d, pm\.start_servers=%d, pm\.min_spare_servers=%d, pm\.max_spare_servers=%d$/m',
[$cpus, $memory, ...$expected],
), $container->logs());
}

/**
* Settings of the sizing, see testPhpFpmPoolIsSizedToTheLimitsOfTheContainer(): the environment, a pool file
* www.conf of your own if not empty, and pm.max_children, pm.start_servers, pm.min_spare_servers and
* pm.max_spare_servers.
*
* @return iterable<string, array{array<string, string>, string, list<int>}>
*/
public static function phpFpmPoolSizes(): iterable
{
yield 'the limits' => [[], '', [4, 2, 1, 4]];
yield 'FPM_PM_MAX_CHILDREN' => [['FPM_PM_MAX_CHILDREN' => '7'], '', [7, 2, 1, 4]];
yield 'fpm.pool.pm.max_children' => [['fpm.pool.pm.max_children' => '3'], '', [3, 2, 1, 3]];
yield 'FPM_AUTO_CHILD_MEMORY and PHP_OPCACHE_MEMORY_CONSUMPTION' => [['FPM_AUTO_CHILD_MEMORY' => '64M', 'PHP_OPCACHE_MEMORY_CONSUMPTION' => '384'], '', [6, 2, 1, 4]];
yield 'FPM_AUTO_CHILDREN_PER_CPU' => [['FPM_AUTO_CHILDREN_PER_CPU' => '1'], '', [2, 1, 1, 2]];
yield 'FPM_AUTO_SIZE' => [['FPM_AUTO_SIZE' => '0'], '', [5, 2, 1, 3]];
yield 'a pool file of your own' => [[], "[www]\npm.max_children = 20\n", [20, 2, 1, 3]];
}

/**
* With --cpus 2 --memory 1g, in short runs of php-fpm -tt: (1024 MB - 256 MB of OPcache - 256 MB) / 128 MB give
* four workers, two CPUs eight, so pm.max_children is 4, pm.min_spare_servers 1 (half the CPUs),
* pm.max_spare_servers 4 (two per CPU, at most pm.max_children) and pm.start_servers 2. A value that is set stays,
* and the others fit it: with seven workers, still at most four spare ones; with three, three.
* FPM_AUTO_CHILD_MEMORY=64M and PHP_OPCACHE_MEMORY_CONSUMPTION=384 give (1024 - 384 - 256) / 64 = 6 workers,
* FPM_AUTO_CHILDREN_PER_CPU=1 two. FPM_AUTO_SIZE=0 and a pool file of your own keep the values of the pool files.
* The configuration test succeeds.
*
* @param array<string, string> $environment
* @param list<int> $expected
*/
#[DataProvider('phpFpmPoolSizes')]
public function testPhpFpmPoolIsSizedToTheLimitsOfTheContainer(array $environment, string $poolFile, array $expected): void
{
// the pool file has to be there when the entrypoint sizes the pool, so the command runs the entrypoint again
$command = $poolFile === '' ? ['php-fpm', '-tt'] : [
'bash', '-c', 'printf %s ' . escapeshellarg($poolFile) . ' > /opt/docker/etc/php/fpm/pool.d/www.conf && exec /entrypoint php-fpm -tt',
];
$result = $this->runContainer($command, $environment, ['--cpus', '2', '--memory', '1g']);
self::assertSame(0, $result->exitCode, $result->describe());
self::assertSame($expected, self::phpFpmProcessManager($result->stderr));
}

/**
* Sends $requests requests that sleep for $seconds to PHP-FPM at once, and returns the largest number of workers
* seen until $within seconds after they started. Waits until the requests ended.
Expand All @@ -233,4 +311,49 @@ private function phpFpmWorkersDuring(Container $container, int $requests, int $s

return $workers;
}

/**
* The CPUs and the memory in MB of $container as the entrypoint sees them: the CPUs it may run on and the memory of
* the host, or the limits of cgroup v2 or v1 where they are lower. A CPU limit is rounded up.
*
* @return array{int, int}
*/
private function containerResources(Container $container): array
{
$lines = explode("\n", trim($this->stdout(
"nproc; awk '/^MemTotal:/ { print \$2 }' /proc/meminfo;"
. ' cat /sys/fs/cgroup/cpu.max 2>/dev/null || echo "$(cat /sys/fs/cgroup/cpu/cpu.cfs_quota_us) $(cat /sys/fs/cgroup/cpu/cpu.cfs_period_us)";'
. ' cat /sys/fs/cgroup/memory.max 2>/dev/null || cat /sys/fs/cgroup/memory/memory.limit_in_bytes',
$container,
)));
self::assertCount(4, $lines, implode("\n", $lines));
$cpus = (int) $lines[0];
$memory = intdiv((int) $lines[1], 1024);
[$quota, $period] = explode(' ', $lines[2]) + ['', ''];
if (ctype_digit($quota) && ctype_digit($period) && (int) $period > 0) {
$cpus = min($cpus, intdiv((int) $quota + (int) $period - 1, (int) $period));
}

if (ctype_digit($lines[3])) {
$memory = min($memory, intdiv((int) $lines[3], 1048576));
}

return [$cpus, $memory];
}

/**
* pm.max_children, pm.start_servers, pm.min_spare_servers and pm.max_spare_servers in the output of php-fpm -tt.
*
* @return list<int>
*/
private static function phpFpmProcessManager(string $configuration): array
{
return array_map(static function (string $directive) use ($configuration): int {
if (preg_match('/NOTICE: \t' . preg_quote($directive, '/') . ' = (\d+)$/m', $configuration, $matches) !== 1) {
self::fail($directive . ' should be in the configuration: ' . $configuration);
}

return (int) $matches[1];
}, ['pm.max_children', 'pm.start_servers', 'pm.min_spare_servers', 'pm.max_spare_servers']);
}
}
2 changes: 1 addition & 1 deletion ci/image-tests/Checks/PhpProductionChecks.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function testOpcacheSettingsForProduction(): void
self::assertSame([
'opcache.memory_consumption' => '256',
'opcache.interned_strings_buffer' => '16',
'opcache.max_accelerated_files' => '7963',
'opcache.max_accelerated_files' => '32531',
], $this->phpSettings(['opcache.memory_consumption', 'opcache.interned_strings_buffer', 'opcache.max_accelerated_files']));
}
}
8 changes: 5 additions & 3 deletions ci/image-tests/Docker/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,16 +77,18 @@ public static function start(string $image, array $directories, array $labels =

/**
* Creates a container like start(), runs it until its command exits and removes it. Returns the output and the
* exit code of the command, e.g. of ['root', 'id', '-un'] through the entrypoint of the image.
* exit code of the command, e.g. of ['root', 'id', '-un'] through the entrypoint of the image. $options are further
* options of docker create, e.g. ['--cpus', '2'].
*
* @param list<string> $directories
* @param array<string, string> $labels
* @param array<string, string> $environment
* @param list<string> $command
* @param list<string> $options
*/
public static function run(string $image, array $directories, array $labels, array $environment, array $command): CommandResult
public static function run(string $image, array $directories, array $labels, array $environment, array $command, array $options = []): CommandResult
{
$container = self::create([], $image, $directories, $labels, $environment, $command);
$container = self::create($options, $image, $directories, $labels, $environment, $command);
try {
$process = new Process(['docker', 'start', '--attach', $container->id]);
$process->setTimeout(self::COMMAND_TIMEOUT);
Expand Down
8 changes: 5 additions & 3 deletions ci/image-tests/ImageTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -345,14 +345,16 @@ protected function commandLines(?Container $container = null): array

/**
* Runs $command in a new container of the image, through its entrypoint, and returns the result once the command
* exits. The container gets the files of Fixtures/ too and is removed afterwards.
* exits. The container gets the files of Fixtures/ too and is removed afterwards. $options are further options of
* docker create, e.g. limits such as ['--cpus', '2'].
*
* @param list<string> $command
* @param array<string, string> $environment
* @param list<string> $options
*/
protected function runContainer(array $command, array $environment = []): CommandResult
protected function runContainer(array $command, array $environment = [], array $options = []): CommandResult
{
return Container::run(self::image()->reference, [self::FIXTURES, self::HOOKS], self::labels(), $environment, $command);
return Container::run(self::image()->reference, [self::FIXTURES, self::HOOKS], self::labels(), $environment, $command, $options);
}

/**
Expand Down
6 changes: 3 additions & 3 deletions conf/dockerhub.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ built:
- { label: 'Known issues', path: 'docs/known-issues.md' }
php:
short: 'PHP-FPM on the official PHP image, configured with environment variables; Debian and Alpine'
intro: 'PHP-FPM on top of the official PHP image, with the webdevops entrypoint, `supervisord`, cron, syslog-ng and the `application` user. PHP-FPM listens on port `9000`. For a web server in the same container, use [`webdevops/php-nginx`](https://hub.docker.com/r/webdevops/php-nginx) or [`webdevops/php-apache`](https://hub.docker.com/r/webdevops/php-apache).'
intro: 'PHP-FPM on top of the official PHP image, with the webdevops entrypoint, `supervisord`, cron, syslog-ng and the `application` user. PHP-FPM listens on port `9000`. At every start, PHP-FPM sizes its pool of workers to the CPU and memory limits of the container, or to the host without limits, see [Size of the PHP-FPM pool](docs/environment-variables.md#size-of-the-php-fpm-pool). For a web server in the same container, use [`webdevops/php-nginx`](https://hub.docker.com/r/webdevops/php-nginx) or [`webdevops/php-apache`](https://hub.docker.com/r/webdevops/php-apache).'
note: 'Always use one of the tags below: an image without a tag (`latest`) and the `alpine` tag are old builds from 2019 and 2020 that get no updates, see [Known issues](docs/known-issues.md#latest-and-alpine-tags-of-the-php-images).'
example:
lang: 'yaml'
Expand Down Expand Up @@ -113,7 +113,7 @@ built:
- { label: 'Known issues', path: 'docs/known-issues.md' }
php-nginx:
short: 'PHP-FPM and Nginx in one container on the official PHP image; Debian and Alpine'
intro: '[`webdevops/php`](https://hub.docker.com/r/webdevops/php) plus Nginx. Nginx serves `/app` and passes PHP requests to PHP-FPM in the same container. Ports: `80` (HTTP) and `443` (HTTPS with a self-signed certificate).'
intro: '[`webdevops/php`](https://hub.docker.com/r/webdevops/php) plus Nginx. Nginx serves `/app` and passes PHP requests to PHP-FPM in the same container. Ports: `80` (HTTP) and `443` (HTTPS with a self-signed certificate). At every start, PHP-FPM sizes its pool of workers to the CPU and memory limits of the container, or to the host without limits, see [Size of the PHP-FPM pool](docs/environment-variables.md#size-of-the-php-fpm-pool).'
note: 'Always use one of the tags below: an image without a tag (`latest`) and the `alpine` tag are old builds from 2019 and 2020 that get no updates, see [Known issues](docs/known-issues.md#latest-and-alpine-tags-of-the-php-images).'
example:
lang: 'yaml'
Expand Down Expand Up @@ -158,7 +158,7 @@ built:
- { label: 'Known issues', path: 'docs/known-issues.md' }
php-apache:
short: 'PHP-FPM and Apache in one container on the official PHP image; Debian and Alpine'
intro: '[`webdevops/php`](https://hub.docker.com/r/webdevops/php) plus Apache. Apache serves `/app` and passes PHP requests to PHP-FPM in the same container. Ports: `80` (HTTP) and `443` (HTTPS with a self-signed certificate).'
intro: '[`webdevops/php`](https://hub.docker.com/r/webdevops/php) plus Apache. Apache serves `/app` and passes PHP requests to PHP-FPM in the same container. Ports: `80` (HTTP) and `443` (HTTPS with a self-signed certificate). At every start, PHP-FPM sizes its pool of workers to the CPU and memory limits of the container, or to the host without limits, see [Size of the PHP-FPM pool](docs/environment-variables.md#size-of-the-php-fpm-pool).'
note: 'Always use one of the tags below: an image without a tag (`latest`) and the `alpine` tag are old builds from 2019 and 2020 that get no updates, see [Known issues](docs/known-issues.md#latest-and-alpine-tags-of-the-php-images).'
example:
lang: 'yaml'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ go-replace --mode=lineinfile --regex \
-s '^[\s;]*opcache.validate_timestamps[\s]*=' -r 'opcache.validate_timestamps = 1' \
-s '^[\s;]*opcache.revalidate_freq[\s]*=' -r 'opcache.revalidate_freq = 0' \
-s '^[\s;]*opcache.interned_strings_buffer[\s]*=' -r 'opcache.interned_strings_buffer = 16' \
-s '^[\s;]*opcache.max_accelerated_files[\s]*=' -r 'opcache.max_accelerated_files = 7963' \
-s '^[\s;]*opcache.max_accelerated_files[\s]*=' -r 'opcache.max_accelerated_files = 32531' \
-- /opt/docker/etc/php/php.webdevops.ini
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ go-replace --mode=lineinfile --regex \
-s '^[\s;]*opcache.validate_timestamps[\s]*=' -r 'opcache.validate_timestamps = 1' \
-s '^[\s;]*opcache.revalidate_freq[\s]*=' -r 'opcache.revalidate_freq = 0' \
-s '^[\s;]*opcache.interned_strings_buffer[\s]*=' -r 'opcache.interned_strings_buffer = 16' \
-s '^[\s;]*opcache.max_accelerated_files[\s]*=' -r 'opcache.max_accelerated_files = 7963' \
-s '^[\s;]*opcache.max_accelerated_files[\s]*=' -r 'opcache.max_accelerated_files = 32531' \
-- /opt/docker/etc/php/php.webdevops.ini
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ go-replace --mode=lineinfile --regex \
-s '^[\s;]*opcache.validate_timestamps[\s]*=' -r 'opcache.validate_timestamps = 1' \
-s '^[\s;]*opcache.revalidate_freq[\s]*=' -r 'opcache.revalidate_freq = 0' \
-s '^[\s;]*opcache.interned_strings_buffer[\s]*=' -r 'opcache.interned_strings_buffer = 16' \
-s '^[\s;]*opcache.max_accelerated_files[\s]*=' -r 'opcache.max_accelerated_files = 7963' \
-s '^[\s;]*opcache.max_accelerated_files[\s]*=' -r 'opcache.max_accelerated_files = 32531' \
-- /opt/docker/etc/php/php.webdevops.ini
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ go-replace --mode=lineinfile --regex \
-s '^[\s;]*opcache.validate_timestamps[\s]*=' -r 'opcache.validate_timestamps = 1' \
-s '^[\s;]*opcache.revalidate_freq[\s]*=' -r 'opcache.revalidate_freq = 0' \
-s '^[\s;]*opcache.interned_strings_buffer[\s]*=' -r 'opcache.interned_strings_buffer = 16' \
-s '^[\s;]*opcache.max_accelerated_files[\s]*=' -r 'opcache.max_accelerated_files = 7963' \
-s '^[\s;]*opcache.max_accelerated_files[\s]*=' -r 'opcache.max_accelerated_files = 32531' \
-- /opt/docker/etc/php/php.webdevops.ini
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ go-replace --mode=lineinfile --regex \
-s '^[\s;]*opcache.validate_timestamps[\s]*=' -r 'opcache.validate_timestamps = 1' \
-s '^[\s;]*opcache.revalidate_freq[\s]*=' -r 'opcache.revalidate_freq = 0' \
-s '^[\s;]*opcache.interned_strings_buffer[\s]*=' -r 'opcache.interned_strings_buffer = 16' \
-s '^[\s;]*opcache.max_accelerated_files[\s]*=' -r 'opcache.max_accelerated_files = 7963' \
-s '^[\s;]*opcache.max_accelerated_files[\s]*=' -r 'opcache.max_accelerated_files = 32531' \
-- /opt/docker/etc/php/php.webdevops.ini
Loading
Loading