Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dynamically set php-fpm workers in docker containers.
#!/usr/bin/env bash
set -eo pipefail
logger() {
printf '%s (%s) %s [%s]: %s\n' "$(date)" "$(whoami)" "${BASH_SOURCE}" "${1}" "${2}"
}
# determine maxprocs according to cgroup-mem-limit
memory_available="$(cat /sys/fs/cgroup/memory/memory.limit_in_bytes)"
memory_per_proc="$(php-memory-limit.php)"
php_num_procs="$(echo "$((memory_available / memory_per_proc))" | awk '{print int($1)}')"
logger "INFO" "memory available: ${memory_available} / memory per proc: ${memory_per_proc} / php num procs: ${php_num_procs}"
sed -i '/^pm/d' /usr/local/etc/php-fpm.d/www.conf
printf 'pm = static\npm.max_children = %d\n' "${php_num_procs}" >> /usr/local/etc/php-fpm.d/www.conf
# passthrough to original entrypoint
exec docker-php-entrypoint "${@}"
#!/usr/bin/env php
<?php
# https://www.php.net/manual/en/function.ini-get.php#refsect1-function.ini-get-examples
function return_bytes($val) {
$val = trim($val);
$mod = strtolower(substr($val, -1));
$val = (int) substr($val, 0, -1);
switch($mod) {
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}
echo return_bytes(ini_get('memory_limit')) . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment