This guide walks you through configuring PHP to store session data in Memcached while running Nginx on Debian. By offloading sessions from disk to memory, you get faster session reads/writes and a central store that can be shared across multiple web servers. You’ll need a Debian server with Nginx and PHP already installed, plus root or sudo access.
What You’ll Need
- A Debian server (10, 11, or 12) with Nginx installed and running.
- PHP-FPM installed and configured to work with Nginx (e.g., via
php-fpm). - Root or sudo access to install packages and edit configuration files.
- Basic familiarity with the command line and editing files in a terminal.
Step-by-Step
- Install Memcached and the PHP extension
Run the following commands to install Memcached and the PHP Memcached extension (which is more feature-rich than the older memcache extension):sudo apt update sudo apt install memcached php-memcachedThis installs the Memcached server and the PHP extension. The extension will be enabled automatically.
- Verify Memcached is running
Check the service status and confirm it’s listening on the default port (11211):sudo systemctl status memcached ss -tulpn | grep 11211If it’s not running, start it with
sudo systemctl start memcachedand enable it to start on boot withsudo systemctl enable memcached. - Find your PHP-FPM configuration
The PHP configuration file is usually at/etc/php/<version>/fpm/php.ini(e.g.,/etc/php/8.2/fpm/php.ini). Find your version withphp -v. - Edit php.ini to use Memcached for sessions
Open the file with sudo:sudo nano /etc/php/<version>/fpm/php.iniLocate the
session.save_handlerandsession.save_pathlines. Change them to:session.save_handler = memcached session.save_path = "127.0.0.1:11211"If you have multiple Memcached servers, you can list them comma-separated, e.g.,
"server1:11211,server2:11211". - Restart PHP-FPM
After saving the changes, restart PHP-FPM to apply them:sudo systemctl restart php-<version>-fpmReplace
<version>with your PHP version (e.g.,php8.2-fpm). - Test that sessions are stored in Memcached
Create a simple PHP test file in your web root (e.g.,/var/www/html/test.php) with the following content:<?php session_start(); $_SESSION['test'] = 'hello'; echo session_id(); ?>Access it via your browser (e.g.,
http://your-server/test.php). Then, from the command line, check Memcached for the session key:echo 'stats items' | nc 127.0.0.1 11211You should see an item count that increases. To see the actual key, use
stats cachedump <slab> <limit>(you may need to installlibmemcached-toolsfor easier debugging). - Optional: Tune Memcached for session storage
Edit/etc/memcached.confto adjust memory (default 64MB) and other settings. For example, to set 256MB:-m 256Restart Memcached after changes:
sudo systemctl restart memcached.
Common Mistakes
- Using the wrong PHP extension – The
php-memcache(without ‘d’) uses a different save_handler (memcache). Make sure you installedphp-memcachedand usesession.save_handler = memcached. - Forgetting to restart PHP-FPM – Changes to php.ini only take effect after restarting PHP-FPM.
- Memcached not running – If the service is down, PHP will fail to write sessions, causing errors or blank pages.
- Firewall blocking port 11211 – If Memcached is on a different server, ensure the port is open and accessible.
- Session path syntax – For memcached, the path is a comma-separated list of
host:portwithout any extra characters.
Tips
- Use a Unix socket for local connections – For better performance, configure Memcached to listen on a Unix socket (e.g.,
-s /tmp/memcached.sock) and setsession.save_pathtounix:///tmp/memcached.sock. - Set a reasonable session lifetime – Memcached evicts data when memory is full, so set
session.gc_maxlifetimeto a value that matches your needs (e.g., 1440 seconds). - Monitor Memcached usage – Use
memcached-tool(fromlibmemcached-tools) orecho stats | ncto check hit rates and memory usage. - Consider sticky sessions if using multiple web servers – If you have a load balancer, you can either share Memcached instances or use sticky sessions to avoid cross-server session issues.
Troubleshooting
If sessions are not working, follow these steps:
- Check PHP error logs – Look at
/var/log/php8.x-fpm.logor the Nginx error log for messages about session save handler failures. - Verify Memcached is accessible – Run
telnet 127.0.0.1 11211and typestats. If you get a connection refused, Memcached isn’t running. - Confirm the extension is loaded – Run
php -m | grep memcachedto ensure the extension is active. - Check php.ini values – Run
php -i | grep session.saveto see the effective settings. If they don’t match your edits, you may have edited the wrong php.ini (e.g., CLI vs FPM). - Test with a simple script – Create a script that writes a session and then reads it back; if it fails, the issue is likely configuration.
- Ensure permissions are correct – If using a Unix socket, make sure the PHP-FPM user (usually
www-data) has read/write access to the socket file.
Frequently Asked Questions
What is the difference between memcache and memcached extensions?
The memcache extension is older and less feature-rich. memcached is a newer, more maintained extension with better performance and support for binary protocol, SASL authentication, and more.
Can I use Memcached for sessions across multiple servers?
Yes, that’s a common use case. Point all servers to the same Memcached server (or cluster) in session.save_path. However, ensure low latency between servers and consider using a dedicated Memcached cluster for reliability.
How do I set session lifetime with Memcached?
Set session.gc_maxlifetime in php.ini (default 1440 seconds). Memcached will expire keys based on that value, but note that Memcached also evicts data when memory is full, so ensure enough memory is allocated.
What happens if Memcached goes down?
PHP will fail to read/write sessions, causing errors or redirect loops. For high availability, use a Memcached cluster or have a fallback session handler (e.g., files) as a backup.
Is it safe to store sessions in Memcached?
Yes, but keep in mind that Memcached has no built-in authentication or encryption. If your Memcached server is exposed to untrusted networks, secure it with a firewall or use SASL authentication.
Can I use both file and Memcached sessions?
Not simultaneously. PHP uses one save handler at a time. You can switch between them, but you cannot have both active for the same PHP process.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Affordable Pickup Trucks: Top Picks & Costs28,554 USD
- Halloween Desk Accessories: Spooky Picks
- Capture Cards: What They Do & How to Use Them
- Affordable Family Sedan: Quietly Reliable?
- Binge-Worthy Paramount Shows to Finish in One Sitting
- Coupe High Octane Fun Sedan? Truth vs Hype