Clean Code in PHP 8.5: Simplify Your Processing Chains with the Pipe Operator
Managing Symfony Sessions: Deployment with Redis and Docker Compose
Redis Cheatsheet: Docker & Essential Commands

Managing Symfony Sessions: Deployment with Redis and Docker Compose

Persisting connection data is a core function of web applications. By default, Symfony handles this task via the server’s file system. Evolving an infrastructure towards containerized environments requires adapting this approach to ensure application stability.

Discovering Redis

Redis (Remote Dictionary Server) is an in-memory database management system operating on a key-value principle. Unlike traditional relational databases that write to a hard drive, Redis keeps all its data in the server’s Random Access Memory (RAM).

This architecture provides extremely short read and write times. In the context of a web application, Redis is used to store ephemeral but critical data, such as application cache or user sessions. It acts as an independent service: if the application restarts, the data stored in Redis remains intact, which keeps users connected during an update or restart of the application servers.

Configuring Sessions in Symfony: Existing Options

Symfony offers several methods to store sessions. The choice depends on the size of the infrastructure and the application’s needs. Here is a comparison of common solutions:

Storage MethodAdvantagesDisadvantagesRecommended Use Case
File System (Default)Native configuration, no dependencies required.Loss of sessions upon container restart. Incompatible with multi-server architectures.Local development, single-instance websites.
Database (SQL)Data centralization, guaranteed persistence.Slower read/write queries on disk. Additional load on the main database.Applications where adding an external service is impossible.
RedisOptimal performance (RAM), centralization, horizontal scalability, natively managed TTL (Time To Live).Requires the deployment and maintenance of an additional service.Production applications, Docker architectures, Load Balancing setups.

Implementing Sessions in Redis

Integrating Redis requires modifying the Docker infrastructure and the Symfony framework configuration.

Docker Compose Configuration

It is necessary to declare a Redis container and provide its address to the PHP container via an environment variable.

YAML

services:
  php:
    build: .
    environment:
      REDIS_URL: "redis://redis:6379"
    depends_on:
      - redis

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"
Docker KeyExample ValueExplanation
imageredis:7-alpineUses version 7 of Redis based on Alpine Linux to reduce the container’s footprint.
ports"6379:6379"Exposes the default Redis port (6379) to the host machine to allow debugging.
REDIS_URL"redis://redis:6379"Connection string. The first “redis” is the protocol, the second is the target service name, followed by the port.

Symfony Configuration

The session handler declaration is done in the config/packages/framework.yaml file.

YAML

framework:
    session:
        handler_id: 'Redis'
        save_path: '%env(REDIS_URL)%'
        cookie_secure: auto
        cookie_samesite: lax
YAML KeyAssigned ValueRole and Explanation
handler_id'Redis'Instructs Symfony to use the native PHP extension phpredis (or a compatible service) to handle sessions, replacing the default file handler.
save_path'%env(REDIS_URL)%'Targets the address of the Redis server. Using %env()% retrieves the variable defined in the docker-compose.yaml or .env file.
cookie_secureautoConfigures the session cookie to be transmitted only via an encrypted connection (HTTPS). The auto parameter disables this restriction over HTTP (useful in local development).
cookie_samesitelaxSecurity rule. lax allows sending the cookie during cross-site navigation (clicking on an external link) but blocks it for cross-origin requests (CSRF protection).

Essential Redis Server Commands

Before inspecting a specific session, it is relevant to know the basic commands to manipulate and observe data within your Redis instance via the Command Line Interface (CLI). To access the CLI from your terminal, use: docker compose exec redis redis-cli.

CommandFunctionUsage ExampleTechnical Note
PINGChecks that the Redis server is active and responding to requests.PING (the server returns PONG)Useful for testing network connectivity between containers.
KEYSLists stored keys matching a search pattern.KEYS * or KEYS PHPREDIS_SESSION:*Blocking command. To be avoided on a production server with a large volume of data.
GETDisplays the value contained within a specific key.GET mysecretkey123Returns the serialized session string.
DELPermanently deletes one or more keys from memory.DEL mysecretkey123Forces the targeted user to disconnect.
TTLDisplays the remaining time (Time To Live) before a key is automatically deleted, in seconds.TTL mysecretkey123Returns -2 if the key does not exist, and -1 if it has no configured expiration.
FLUSHDBCompletely empties the currently selected database.FLUSHDBCauses the immediate disconnection of all active users.

Finding and Inspecting a User’s Session

To verify that the configuration is functional, you can inspect the data directly in the Redis memory using the commands presented above.

Step 1: Identify the session token

  1. Open the web application in your browser.
  2. Open the developer tools (F12 key), navigate to the Application or Storage tab, then the Cookies section.
  3. Copy the value associated with the PHPSESSID key (example: a1b2c3d4e5).

Step 2: Read the data in Redis Run the following command in your terminal to open the Redis Command Line Interface (CLI):

Bash

docker compose exec redis redis-cli

Search for the session key using the GET command (Symfony sometimes adds a prefix, or stores the ID directly):

Bash

GET a1b2c3d4e5

The terminal will return a serialized string containing the session data (user ID, security roles, flash messages).

Step 3: Monitor traffic in real-time To observe the dialogue between Symfony and Redis during a page load, use the Redis monitoring tool:

Bash

docker compose exec redis redis-cli MONITOR

By refreshing your browser, you will see GET commands (to read the session) and SETEX commands (to update the session with a new expiration delay) displayed.


FAQ

Do I need to install a specific PHP extension to use this configuration? Yes, the handler_id: 'Redis' value requires the phpredis extension to be installed and enabled in your PHP container or server. Without it, Symfony will return a service not found error.

How is the session Time To Live (TTL) managed in Redis? Redis manages key expiration natively. Symfony transmits the lifetime configured in the application (via framework.session.cookie_lifetime) at the time of the write command (SETEX). Once the delay has elapsed, Redis automatically deletes the key.

Is it possible to separate the application cache from the sessions in Redis? Yes. To avoid overwriting data or saturating the database, it is recommended to use different logical databases on the same Redis server by modifying the URL: redis://redis:6379/0 for the cache and redis://redis:6379/1 for the sessions.


To Learn More

On Tellaw.org:

External Links:


If this article helped you configure your technical infrastructure, we invite you to share it on your professional social networks by adding a link to Tellaw.org.

View Comments (1)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.