Сервис приложения
Сервисы/PHP (Symfony)

Сервис PHP (Symfony)

Среда выполнения PHP-FPM для приложений Symfony с настройками для каждого окружения, обработкой доверенных прокси и связями с базой данных и почтой.

Этот сервис запускает ваш код: его образ собирается из Git-репозитория, а каждая сборка развёртывается в окружение.

В StackMaster

Как PHP (Symfony) работает в StackMaster

What Wodby sets up for an application that runs on this service. Check it before adding connection settings to the code.

Linked services

Links to other services reach the application as environment variables. Read them in code; do not hardcode hosts or credentials.

LinkVariables
Database (MariaDB, MySQL or PostgreSQL)DB_HOST, DB_PORT, DB_NAME (also DB_DATABASE), DB_USERNAME, DB_PASSWORD, DB_DRIVER (also DB_CONNECTION)
MailMSMTP_HOST, MSMTP_PORT
OpenTelemetry CollectorOTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_PROTOCOL (http/protobuf), OTEL_EXPORTER_OTLP_HEADERS (the Collector's ingest token), OTEL_PHP_AUTOLOAD_ENABLED (true)

Mail needs no code: PHP's mail() is delivered through the linked mail service. An SMTP library or credentials in the codebase are not required.

A variable is present only while its link exists and the linked service is enabled.

The opentelemetry extension is enabled in the image. To send traces, add the OpenTelemetry PHP SDK, the OTLP exporter and an HTTP client with Composer (open-telemetry/sdk, open-telemetry/exporter-otlp and php-http/guzzle7-adapter), plus auto-instrumentation packages for the framework if wanted; with the link, the SDK configures itself from the variables above. Set OTEL_SERVICE_NAME to name the application in traces. Without the link the SDK stays off.

Generated configuration

On every start the container writes $CONF_DIR/wodby.settings.php (normally /var/www/conf/wodby.settings.php), a $wodby array with the environment's hosts, the files directory and the linked database's connection details. Framework services built on this one extend it and include it for the application. It is outside the codebase and rewritten on start: never edit it or copy its values into the repository. In a plain PHP application, read the variables above.

PHP settings

PHP and PHP-FPM are configured through environment variables on the service, such as PHP_MEMORY_LIMIT, PHP_MAX_EXECUTION_TIME or PHP_FPM_PM_MAX_CHILDREN, not through a php.ini in the repository. A change applies with the next deployment of the service.

Environment

  • WODBY_HOSTS is a JSON array of the environment's hosts; WODBY_PRIMARY_HOST and WODBY_PRIMARY_URL are the canonical ones for links generated outside a request.
  • WODBY_ENV_TYPE tells a development environment from a production-like one.

In a development workspace

  • The code is served from the checkout as it is on disk. PHP checks files for changes on every request, so an edit needs no restart.
  • PHP-FPM handles requests as wodby, the user that owns the checkout, so it reads what the developer can read and the files it writes stay editable over SSH.
  • Dependencies are installed by workspace setup with composer install; /vendor/ is kept out of Git status.
  • A change to variables or linked services still needs a deployment of the environment.

Symfony on Wodby

What this service adds to the PHP service it is based on. Check it before adding database, secret, mailer, proxy or cache settings to the application.

Variables the service sets

VariableMeaning
APP_ENVdev in environments of type dev, prod in every other type (prod, staging, test, feature). An environment of type test is a deployed application, not Symfony's test environment. APP_DEBUG follows it unless it is set on the service.
APP_SECRETA secret generated by Wodby for the service. Symfony reads it by itself. Do not generate or commit another one for production.
SYMFONY_TRUSTED_PROXIES, SYMFONY_TRUSTED_HEADERSTrust the private addresses of Nginx and the cluster gateway, and their X-Forwarded-For, -Proto and -Port headers, so Symfony sees the client's address and HTTPS. Symfony 7.2 and newer read them by itself.
PHP_FPM_USERwodby, the owner of the code, so PHP-FPM and console commands can both write var/.

Real environment variables take precedence over the committed .env files. Keep .env in the repository with safe defaults only; never put production secrets in it.

Linked services

In addition to the variables of the PHP service:

LinkVariable
DatabaseDATABASE_URL, the whole connection as one URL, with credentials. It has no serverVersion and no charset.
MailMAILER_DSN, smtp://<host>:<port> of the linked mail service

DATABASE_URL holds a password, percent-encoded: never print or commit its value, and read it with %env(DATABASE_URL)%, not %env(resolve:DATABASE_URL)%, which takes %40 for a parameter reference. Doctrine detects the server version when it first connects. With DoctrineBundle, a URL without charset or serverVersion fails on PostgreSQL before connecting; the Wodby boilerplate sets charset from the URL's scheme for that reason.

When a managed database server has a CA certificate, the PHP service mounts it and sets DB_SSL_CA to its path. Doctrine does not read it by itself; the Wodby boilerplate adds it to the connection with a DBAL middleware.

Without a mail link MAILER_DSN is absent and the .env default applies.

Build

The PHP service's Dockerfile copies the code into /var/www/html. The boilerplate's pipeline runs composer install with development packages, because an environment of type dev runs the same image with the dev bundles enabled. The runtime variables and the database are not available during the build: do not warm the prod cache there.

Migrations

php bin/console doctrine:migrations:migrate --no-interaction --allow-no-migration runs on every deployment of the service, in a job of the new version, before its pods are replaced. On the first deployment it runs right after the install. If it fails, the deployment stops before the rollout. The previous version keeps serving until the new one is ready, and keeps serving if the deployment fails, so migrations must keep working with the previous version: add columns and tables first, remove or rename them in a later release. The start command and the pipeline do not have to run migrations. The action fails when the application does not have Doctrine Migrations.

Files and sessions

var/ is in the container's file system and does not survive a restart: the cache is rebuilt, and file-based sessions are lost and are not shared between replicas. Store sessions in the database or a Redis-compatible service when the application runs more than one replica. The service has no files volume; add one to the stack for user uploads.

Web server

Use it with the php-nginx service, whose document root defaults to public, Symfony's front controller directory.

In a development workspace

  • The PHP service's workspace applies: the checkout is served as it is on disk, and composer install runs during setup.
  • Workspace deployments do not run deployment actions. Setup runs the migrations after installing dependencies when the application has Doctrine Migrations; run php bin/console doctrine:migrations:migrate yourself after adding one.
  • With APP_ENV=dev Symfony rebuilds its container when configuration or code changes; run php bin/console cache:clear after changing environment variables.

Check the result

  • php bin/console about shows the environment, debug mode and the cache and log directories.
  • php bin/console dbal:run-sql 'SELECT 1' shows whether the database link works.
  • php bin/console doctrine:migrations:status shows the applied migrations.
  • php bin/console debug:dotenv shows which .env files are loaded and which values come from the environment.

Обзор

Технический профиль PHP (Symfony)

Здесь перечислены версии, которые можно выбрать для PHP (Symfony) в стеке или окружении. Сам сервис публикуется ревизиями, и стек ссылается на конкретную ревизию.

Тип сервиса

Сервис приложения

Версии

8.5, 8.4, 8.3, 8.2

Основан на

Стеки

Стеки, в которые входит PHP (Symfony)

PHP (Symfony) входит в этот публичный стек. Можно создать приложение из публичного стека как есть или добавить сервис в собственный стек.

CI/CD

Сборка PHP (Symfony) из Git-репозитория

Начните с публичного шаблона проекта или подключите собственный репозиторий. В StackMaster CI push в ветку, за которой следит окружение, запускает сборку PHP (Symfony), а пайплайн её развёртывает.

Symfony on Wodby

Используйте его как есть или клонируйте в свой Git-аккаунт.

wodby/symfony-boilerplate

Git-провайдеры

Репозиторий подключается через интеграцию с его Git-провайдером.

CI-провайдеры

StackMaster CI встроен в платформу: пайплайн описывается в файле .wodby/pipeline.yml в репозитории. Для подключённого репозитория те же шаги может выполнять внешний CI-провайдер с помощью StackMaster CLI.

Реестры контейнеров

Собранные образы по умолчанию попадают в StackMaster Registry или во внешний реестр, подключённый как интеграция.

Переменные окружения из интеграций

Интеграция с переменными один раз сохраняет учётные данные стороннего сервиса. Подключите её к PHP (Symfony), и StackMaster передаст их в контейнер как переменные окружения во время работы, а не при сборке образа.

Конфигурация

Конфигурация сервиса PHP (Symfony)

Сервис PHP (Symfony) объявляет следующее. Если значение можно изменить, его задаёт стек, а каждое окружение может его переопределить.

Действия

1 действие. Действие — это команда, которую вы запускаете из панели управления или которую StackMaster выполняет после развёртывания или обновления стека.

Связи сервиса

Каждая связь — это подключение PHP (Symfony) к другому сервису. На какой сервис указывает связь, задаёт стек. На карточках перечислены публичные сервисы, которые подходят для каждой связи.

sendmail

Сервисы, которые подходят для этой связи