I recently started using new AWS Elasticbeanstalk Nginx (Amazon Linux 2). I notice after any deployment or restart on Elasticbeanstalk the PHP session lost (if the user is logged in, he will be logged out). Previously I was using Amazon Linux 1 version which was running on Apache and haven't faced this issue, is there any way to keep PHP session after ?
This is due to a change in Amazon Linux 2 where PHP is now hosted by the PHP-FPM systemd service (the previous Amazon Linux version did not use PHP-FPM or systemd). The method for tracking sessions in the default PHP configuration provided by ElasticBeanstalk is to use files in the /tmp
directory. However, systemd's "PrivateTmp" is enabled by default, which creates a unique directory for the PHP-FPM service to use when running. As soon as the PHP-FPM service is stopped, systemd deletes this special "private" /tmp
, which deletes all the session files.
Whenever PHP ElasticBeanstalk deploys a new version, this PHP-FPM service is stopped and restarted, resulting in the loss of sessions.
There are a couple options to address this issue:
-> Configure PHP to use something like memcached/redis/etc to manage sessions, instead of using the filesystem. This is probably the most secure solution.
Or,
-> Configure your Amazon Linux 2 ElasticBeanstalk instances to handle these session files in the /tmp
directory proper, instead of the "private" /tmp
directory provided by systemd.
This can be easily done by adding the following post-deploy configuration script into your project under the path: .platform/hooks/postdeploy/phpfpm_noprivatetmp.sh
#!/bin/bash -e
# change PrivateTmp from true to false, then reload/restart the systemd service
sed -i 's/PrivateTmp=true/PrivateTmp=false/' /usr/lib/systemd/system/php-fpm.service
# wait a moment...
sleep 2
sudo systemctl daemon-reload
# wait a moment...
sleep 2
sudo systemctl restart php-fpm.service
This will disable the "PrivateTmp" feature, causing the session files to be stored in the "real" /tmp
directory, and deploying new versions of your site will no longer cause everyone to get logged out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With