同一Memcached服务器能否支持多应用实例?Docker缓存失效问题咨询
Hey there! Let's break down your concerns step by step—this behavior isn't what you should expect from Memcached, and sharing a single server is totally feasible once you fix the root issue.
Is this expected behavior?
Absolutely not. Memcached is designed to retain data in memory as long as:
- The server doesn't restart (since it's an in-memory store, all data is lost on reboot)
- The keys don't expire (based on your TTL settings)
- The server doesn't evict keys due to memory pressure (via its LRU algorithm)
- No one explicitly runs a
flush_allcommand to clear all data
The fact that your existing data gets wiped only when starting a new client instance (Node 2) suggests something in your setup is triggering a full cache clear during client initialization, or your Memcached server is restarting coincidentally when Node 2 launches.
Do I need to deploy a separate Memcached server for each client instance?
No way—this defeats the whole purpose of using a shared cache. Memcached is built to handle multiple concurrent clients (across containers, servers, or languages) connecting to the same server and accessing the same pool of cached data. Deploying separate servers would waste resources and eliminate the shared cache benefit you're aiming for.
Can I share the same Memcached server without losing data?
Yes, and your later test already proves this works! When you re-stored data from Node 1 after Node 2 was running, Node 2 could query it perfectly—this confirms the shared server setup is functional when the initial clearing issue is resolved.
How to fix the initial data loss issue:
- Check your Spymemcached initialization code: Look for any accidental calls to
flush_allwhen the client starts. Some frameworks or custom setup scripts might include this to "reset" the cache, but it will wipe all existing data across all clients. - Verify Memcached container stability: Run
docker logs <your-memcached-container-id>to check if the Memcached server restarted when Node 2 launched. If the container rebooted (e.g., due to resource limits, misconfiguration, or a crash), all in-memory data would be lost. - Confirm Docker network setup: Ensure all your application containers (Node 1, Node 2) are connected to the same Docker network, and they're using the correct Memcached container name/IP to connect (avoid using
localhostinside containers—it refers to the container itself, not the host or other containers). For example, if your Memcached container is namedmemcached, usememcached:11211as the connection address. - Optional: Add persistence (if needed): Memcached is in-memory by default, but if you need to retain data across server restarts, you can use tools like
memcached-toolto export/import data, or consider a cache solution with built-in persistence like Redis. But for most cache use cases, reloading data from your source system after a restart is sufficient.
内容的提问来源于stack exchange,提问作者Eder F. Freitas

