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 Method | Advantages | Disadvantages | Recommended 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. |
| Redis | Optimal 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 Key | Example Value | Explanation |
|---|---|---|
| image | redis:7-alpine | Uses 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 Key | Assigned Value | Role 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_secure | auto | Configures 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_samesite | lax | Security 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.
| Command | Function | Usage Example | Technical Note |
|---|---|---|---|
| PING | Checks that the Redis server is active and responding to requests. | PING (the server returns PONG) | Useful for testing network connectivity between containers. |
| KEYS | Lists 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. |
| GET | Displays the value contained within a specific key. | GET mysecretkey123 | Returns the serialized session string. |
| DEL | Permanently deletes one or more keys from memory. | DEL mysecretkey123 | Forces the targeted user to disconnect. |
| TTL | Displays the remaining time (Time To Live) before a key is automatically deleted, in seconds. | TTL mysecretkey123 | Returns -2 if the key does not exist, and -1 if it has no configured expiration. |
| FLUSHDB | Completely empties the currently selected database. | FLUSHDB | Causes 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
- Open the web application in your browser.
- Open the developer tools (F12 key), navigate to the Application or Storage tab, then the Cookies section.
- Copy the value associated with the
PHPSESSIDkey (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:
- Symfony Documentation – Session Configuration
- Redis Documentation – CLI Commands and Memory Management
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.
[…] Managing Symfony Sessions: Deployment with Redis and Docker Compose […]