Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS elastic beanstalk Nginx PHP session lost

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 ?

like image 544
mpoozd Avatar asked Nov 15 '22 03:11

mpoozd


1 Answers

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.

like image 90
DashRantic Avatar answered Feb 02 '23 00:02

DashRantic