phpsymfonyamazon-elastic-beanstalksymfony4symfony-cache

Symfony on AWS EB - Unable to write in the cache directory after cache clear


I am deploying a Symfony 4.4 app to AWS ElasticBeanstalk and noticed that the cache wasn't cleared after each deploy.

The app was running fine though, exception made to the stale cache.

To resolve the cache issue I added the following file:

/.ebextensions/deploy.config

container_commands:
    01-clear-cache:
        command: php bin/console cache:clear --no-warmup --env=prod

That seems to clear the cache but then somehow it changes permissions so that I then get the error when trying to access the app.

Fatal error: Uncaught RuntimeException: Unable to write in the cache directory (/var/app/current/var/cache/prod)

Why does running cache:clear changes permissions and is there a way to avoid that happening, or at least how to resolve afterwards, ie, in the same/another .ebextensions file?


Solution

  • These commands are run by the root user, as specified in the docs.

    The specified commands run as the root user, and are processed in alphabetical order by name. Container commands are run from the staging directory, where your source code is extracted prior to being deployed to the application server. Any changes you make to your source code in the staging directory with a container command will be included when the source is deployed to its final location.

    (Emphasis mine).

    When re-creating the cache, the new directories are owned by root, and your PHP process can't write there if it needs to.

    Execute your command so it runs using the same user than your PHP runtime. E.g. if it runs under the www-data user:

    container_commands:
        01-clear-cache:
            command: sudo -u webapp php bin/console cache:clear --no-warmup --env=prod