Laravel 12会话值刷新即消失问题求助(Docker部署)
Laravel 12 Docker部署会话丢失问题排查方案
问题现象
- 创建会话后刷新页面,会话值立即丢失;用户登录后刷新页面,
auth()->user()返回NULL - 切换
SESSION_DRIVER为file时,storage目录无会话文件生成;切换为database时,sessions表无数据写入 - 测试验证:执行
session(['test' => 123]);后调用dd(session('test'));能获取值,但调换顺序先执行dd(session('test'));再执行session(['test' => 123]);返回NULL
Dockerfile 配置
WORKDIR /var/www/html COPY . /var/www/html ######## Composer.phar ######## RUN curl -s https://getcomposer.org/installer | php \ # move composer into a bin directory you control: && mv composer.phar /usr/local/bin/composer \ # double check composer works && composer about RUN php -m && echo "=============================================" RUN apt-get update && apt-get install -y \ libpng-dev \ libxml2-dev \ libxslt-dev \ libzip-dev \ libsodium-dev RUN docker-php-ext-install \ exif \ opcache \ pcntl \ pdo_mysql \ zip \ sodium \ sockets RUN apt-get update && \ apt-get install -y libfreetype6-dev libjpeg62-turbo-dev libpng-dev && \ docker-php-ext-configure gd --with-freetype=/usr/include/ --with-jpeg=/usr/include/ RUN docker-php-ext-install gd RUN chmod -R 775 /var/www/html RUN chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache # Expose port 8001 and start php-fpm server EXPOSE 8001 CMD ["php-fpm"]
docker-compose.yml web服务配置
web: build: context: . dockerfile: Dockerfile container_name: crypto working_dir: /var/www/html tty: true restart: unless-stopped volumes: - ./:/var/www/html networks: - crypto
排查与解决步骤
检查Web代理配置
- 若使用Nginx作为反向代理,需确保配置中传递Cookie和Host头:
proxy_set_header Cookie $http_cookie; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $remote_addr; - 确认
.env中SESSION_DOMAIN与访问域名一致,本地开发可设为localhost或空字符串
- 若使用Nginx作为反向代理,需确保配置中传递Cookie和Host头:
修复目录权限(针对file驱动)
- Windows挂载目录可能存在权限映射异常,进入容器执行:
mkdir -p storage/framework/sessions chmod -R 777 /var/www/html/storage/framework/sessions chown -R www-data:www-data /var/www/html/storage/framework/sessions
- Windows挂载目录可能存在权限映射异常,进入容器执行:
验证Session中间件
- 检查
app/Http/Kernel.php的web中间件组,确保包含\Illuminate\Session\Middleware\StartSession::class - 确认业务路由都包裹在
web中间件组内,未使用该中间件的路由不会启动Session
- 检查
检查PHP Session配置
- 进入容器执行
php -i | grep session,查看session.save_path是否指向/var/www/html/storage/framework/sessions - 确保
session.cookie_domain与SESSION_DOMAIN匹配,本地HTTP环境需将session.cookie_secure设为Off
- 进入容器执行
Database驱动额外验证
- 确认已生成
sessions表:执行php artisan session:table后运行php artisan migrate - 检查
.env中的数据库连接配置,确保容器内PHP能正常连接数据库
- 确认已生成
清除缓存
- 执行以下命令清除配置、路由和缓存:
php artisan config:clear php artisan route:clear php artisan cache:clear
- 执行以下命令清除配置、路由和缓存:
内容的提问来源于stack exchange,提问作者Burhan Çelebi
相关产品推荐
相关产品推荐

