We use cookies for analytics and advertising. Ads are disabled until you accept advertising cookies. Read our Cookie Policy and Privacy Policy.
Docker Sessions Lost After Redeploy? Fix In-Memory Storage | TVerge Tech
Docker Sessions Lost After Redeploy? Fix In-Memory Storage
Users logged out after every Docker redeploy? Learn why in-memory sessions vanish and how to fix it with Redis, shared state, and safe rolling deploys.
November 15, 2026Nwankwo Ernest Onyebuchi17 min read
Was this useful?
Docker Applications Lose User Sessions After Redeployment: Fix In-Memory Session Storage and Shared State
You ship a small fix, run your deploy, and within seconds your support inbox fills up with the same complaint: "I got logged out." Carts are empty, half-finished forms are gone, and everyone has to sign in again. Nothing is wrong with your authentication code. The problem is where your application keeps its session data.
If your app runs in Docker and stores sessions in process memory, every redeployment destroys them. This guide explains why that happens, how to confirm it, and how to fix it properly with an external session store, a stable secret, persistence settings, and safe deployment habits. The same principles apply to any other state your app keeps in memory.
The main examples use Node.js with Express, because it is a common stack where this bug appears. The reasoning applies equally to Python, Java, PHP, Ruby, and other frameworks, and a later section covers them.
Why Sessions Disappear When You Redeploy a Docker Container
A web session has two parts. The browser holds a cookie that contains a session ID, and the server holds the data that ID points to: who is logged in, what is in the cart, which CSRF token was issued.
In many frameworks the default session store is a plain object inside the application process. The Express session middleware is a well-known example. Its official documentation warns that the default is purposely not designed for production, will leak memory under most conditions, and does not scale past a single process.
Now add Docker. A container is meant to be disposable. When you redeploy, the usual flow is:
Build a new image.
Stop the old container.
Start a new container from the new image.
The old process exits, and everything in its memory goes with it. The new process starts with an empty session store. The browser still sends its old cookie, but the server has no record of that session ID, so it treats the visitor as anonymous.
The container's file system does not help either. According to Docker's storage documentation, changes written inside a container's writable layer are lost when the container is removed, and data that must outlive a container belongs in a volume or an external service.
The result is simple: anything stored only in process memory or in the container's writable layer does not survive a redeploy.
Quick Diagnosis: Is In-Memory Session Storage Your Problem?
Before changing anything, confirm the cause. Several different bugs produce the same "random logouts" symptom.
Symptom checklist
Users are logged out immediately after every deployment or container restart.
Sessions work fine locally with one process but fail when you run two or more replicas.
Logins succeed but the next request behaves as if you were never signed in, and the problem is intermittent.
Your logs show the production warning about the memory session store.
Reproduce it in under two minutes
Sign in to your application in a browser.
Recreate the container: docker compose up -d --force-recreate web.
Reload the page.
If you are signed out, session data was not persisted outside the container. If you stay signed in, look at the other causes below.
Other causes that look identical
Cause
How to recognize it
Random secret generated at startup
The code builds the signing secret from random bytes each time the process starts, so old cookies fail signature checks
Missing proxy trust
Behind a reverse proxy, secure cookies are never set because the app thinks the connection is plain HTTP
Cookie scope mismatch
The cookie Domain, Path, or SameSite settings differ between environments
Multiple replicas without a shared store
Logins work only when the load balancer happens to pick the same container
Short or missing expiry
The store removes sessions sooner than you expect
It is common for more than one of these to be present at once, so work through the whole list rather than stopping at the first match.
Pick a Session Strategy That Survives Redeploys
There is no single correct design. Here are the realistic options and their trade-offs.
Option 1: External key-value store such as Redis
The application stores only the session ID in the cookie, and session data lives in Redis (or a compatible service). Every replica reads from the same place, and a container replacement does not touch the data.
This is the most common fix because it is fast, supports expiry natively, and is supported by almost every framework. The cost is one more service to run and monitor.
Option 2: Database-backed sessions
Sessions go into PostgreSQL, MySQL, or another database you already operate. This adds no new infrastructure and gives you durable storage, but every request becomes a database read, so you need to index the session table and clean up expired rows.
Option 3: Signed or encrypted cookie sessions
All session data is placed inside the cookie itself, signed or encrypted. There is no server-side store, so redeploys cannot lose anything. Limits apply: cookies are small, the data travels with every request, and you cannot easily revoke an individual session before it expires. This works for small, low-risk payloads and is a poor fit for large or sensitive data.
Option 4: Sticky sessions (not a real fix)
Load balancers can route a user to the same container every time. Kubernetes documents this as session affinity. It reduces cross-replica misses, but it does not protect sessions when a container is replaced, and it can create uneven load. Treat it as a stopgap rather than a solution.
Option 5: A mounted volume with a file-based store
You can write session files to a Docker volume. This survives a single container being replaced, but it does not work cleanly across multiple hosts, and file stores can become slow under load. It is usually better to use Redis or a database.
Recommendation: for most production applications, use an external store (Redis or your primary database) and keep the application containers stateless.
Step-by-Step Fix: Express, Redis, and Docker Compose
This walkthrough replaces the in-memory store with Redis and makes the setup safe for redeployment.
Step 1: Install the packages
npm install express-session connect-redis redis
Step 2: Configure the session middleware
import express from "express";
import session from "express-session";
import { RedisStore } from "connect-redis";
import { createClient } from "redis";
if (!process.env.SESSION_SECRET) {
throw new Error("SESSION_SECRET is required");
}
const redisClient = createClient({ url: process.env.REDIS_URL });
redisClient.on("error", (err) => console.error("Redis client error:", err));
await redisClient.connect();
const app = express();
// Required when TLS is terminated by a reverse proxy or load balancer
app.set("trust proxy", 1);
app.use(
session({
store: new RedisStore({
client: redisClient,
prefix: "myapp:sess:",
ttl: 60 * 60 * 24, // seconds
}),
name: "sid",
// Comma-separated list; the first value signs, all values verify
secret: process.env.SESSION_SECRET.split(","),
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: 1000 * 60 * 60 * 24,
},
})
);
A few details matter here:
resave: false and saveUninitialized: false avoid writing a store entry for every anonymous request.
trust proxy lets Express recognize an HTTPS connection forwarded by a proxy, so secure cookies are issued. The Express guide on running behind proxies explains the setting in detail.
A secret array allows rotation. As documented for the middleware, only the first secret signs new cookies while all of them are accepted when verifying, so you can add a new secret at the front without logging everyone out.
Failing fast when the secret is missing prevents a silent fallback to a weak or random value.
Step 3: Keep the secret stable
A very common cause of "everyone is logged out after deploy" is a secret that changes between container starts, for example one generated with random bytes at boot. Generate a strong value once, store it in your secret manager or environment configuration, and pass it into every replica.
You can create a long random value with the Secure Password Generator, which uses the browser's Crypto API locally. Never commit the secret to your repository or bake it into an image.
redis-data:/data mounts a named volume at the path where the official Redis image keeps its data, so session data survives a Redis container restart.
--appendonly yes turns on append-only file persistence. The Redis persistence documentation describes RDB snapshots and AOF logging and explains that AOF records each write so it can be replayed on restart. Choose the persistence mode that matches how much session loss you can tolerate.
depends_on with a health condition makes the app wait until Redis answers. The Docker Compose startup order guide explains why plain start order is not enough.
init: true runs a small init process as PID 1 so signals are forwarded and zombie processes are reaped.
stop_grace_period gives the app time to finish in-flight requests before Docker force-kills it.
Step 5: Handle login safely
Regenerate the session ID when a user signs in so an attacker cannot reuse an ID they planted before login. The middleware exposes req.session.regenerate() for this.
Store only what you need in the session, such as a user ID, and look up everything else from your database. Smaller sessions are faster, easier to expire, and expose less if the store is ever compromised.
Step 6: Shut down gracefully
A redeploy sends SIGTERM to your process. If the app ignores it, Docker waits for the grace period and then kills the container, which can drop in-flight requests and leave the Redis connection half open.
Start the app with the exec form of CMD, for example CMD ["node", "server.js"], rather than a shell wrapper or npm start, so the signal reaches Node directly. For a deeper treatment of draining connections, see our guide to graceful shutdown in Kubernetes, which applies the same principles to Docker.
Test That Sessions Now Survive a Redeploy
Run the check that failed before.
Start the stack in a non-production mode so the cookie works over plain HTTP: NODE_ENV=development docker compose up -d.
Sign in through the browser, or with a cookie jar in curl.
Redeploy only the application container: docker compose up -d --build --force-recreate web.
Reload the page. You should still be signed in.
Restart Redis as well: docker compose restart redis. With persistence enabled, sessions should still be present.
Session values are stored as JSON strings. Paste a value into the JSON Formatter & Validator to read it more easily, and avoid pasting real production session data into any online tool.
If you use signed-cookie sessions instead, the Base64 Encoder & Decoder is handy for inspecting the readable portion of a cookie value during debugging.
Zero-Downtime Deploys and Session Safety
Moving sessions out of memory fixes the main bug. A few other habits keep deployments smooth.
Run more than one replica during rollouts
If you replace your only container, there is always a short window with no server. Starting the new version before stopping the old one, with a health check gating traffic, removes that gap. Because sessions now live in Redis, either version can serve any user.
Keep session data backward compatible
During a rolling deploy, old and new code run side by side and read the same sessions. If the new version renames a session field or changes its shape, the old version may crash or misbehave. Add new fields first, keep reading the old ones for a release or two, and remove them later.
Plan for Redis maintenance
Redis becomes a dependency of every authenticated request. Decide ahead of time what the app should do if it is unreachable. Failing closed, meaning requests that need a session return an error, is safer than silently treating everyone as anonymous or falling back to memory. Monitor memory usage and set an eviction policy deliberately. Managed Redis providers publish their own guidance on this. One example is Railway's Redis cache versus store guide, which advises treating sessions as persistent data and avoiding eviction for them.
Separate caches from sessions
Cache data can be rebuilt, but sessions cannot. If you share one Redis instance between them, an eviction policy tuned for caches may delete live sessions under memory pressure. Use separate instances or databases, or configure each deliberately.
Beyond Sessions: Fix Every Kind of In-Memory Shared State
Sessions are the most visible casualty, but the same mistake hides elsewhere. Any state that must be consistent across replicas, or must survive a restart, does not belong in process memory.
State kept in memory
What breaks
Better home
Login and CSRF tokens
Tokens rejected after redeploy or on another replica
Session store or database
Rate-limit counters
Each replica counts separately, limits reset on restart
A useful rule of thumb is the "kill test": if you can delete any container at any moment without users noticing, your design is stateless enough.
The Same Problem in Other Frameworks
The fix is conceptually identical everywhere: move session data to a shared, durable backend.
Django: sessions can use the database, cache, or cache-plus-database backends, configured through settings. See the Django sessions documentation. A local-memory cache backend has the same per-process problem as MemoryStore.
Flask: the built-in session stores data in a signed client-side cookie, so it survives redeploys as long as the secret key stays the same. See the Flask session documentation. A secret key that changes on each start invalidates every cookie.
Spring Boot:Spring Session moves HTTP session data into Redis or a database, replacing the servlet container's in-memory sessions.
Kubernetes deployments: the same rules apply to pods. Pods are replaced during rollouts, so use an external store and, if you must use session affinity, treat it as an optimization rather than your persistence layer.
Security Checklist for Session Storage
Moving sessions to a shared store is a good moment to review their security.
Mark cookies HttpOnly, and Secure in production.
Choose a deliberate SameSite value for your login flow.
Use long, random secrets and keep them out of source control.
Set sensible expirations and consider shorter idle timeouts for sensitive applications.
Regenerate the session ID on login and privilege changes, and destroy it on logout.
Restrict network access to Redis. Do not publish its port to the internet, and keep it on a private Docker network.
Enable authentication and TLS on Redis when it is reachable beyond a single trusted host.
Avoid storing personal data you do not need inside session objects.
Requirements vary by project, region, and industry, so review your own obligations before collecting or retaining user data.
Common Mistakes to Avoid
Bind-mounting the session store into the image and calling it done. A volume protects files, not in-process memory.
Generating the secret at startup. Every restart invalidates all cookies.
Forgetting trust proxy. Secure cookies silently fail behind a TLS-terminating proxy.
Using sticky sessions as a substitute for shared storage. Replacement and crashes still wipe sessions.
Sharing one Redis with an eviction policy for sessions and caches. Sessions can be evicted under memory pressure.
Running Redis without persistence while treating it as durable. A restart then loses every session.
Skipping health checks. The app starts before Redis is ready and fails its first requests.
Shell-form CMD. The app never receives SIGTERM and gets killed abruptly.
Frequently Asked Questions
Why do my users get logged out every time I redeploy Docker containers?
Your application most likely stores sessions in process memory. Redeploying replaces the container, the old process exits, and its memory is discarded. The browser's cookie then refers to a session that no longer exists. Moving sessions to Redis or a database fixes this.
Will a Docker volume keep my in-memory sessions?
No. A volume persists files, but an in-memory store never writes to disk. You need a store that persists data, or an external service, rather than relying on a volume for the app container.
Do I need Redis, or can I use my existing database?
Either works. A database avoids a new service but adds read load and requires expired-row cleanup. Redis is faster and handles expiry natively, which is why it is the common choice.
Are sticky sessions enough?
Not on their own. They help route requests but do not protect sessions when a container is replaced or crashes. Use them, if at all, alongside a shared store.
Can I use JWTs instead of server-side sessions?
You can, but token-based approaches bring their own trade-offs, including revocation, token size, and storage on the client. Choose the approach based on your authentication framework's guidance rather than only to avoid a session store.
Does this fix apply when I run a single container?
Yes. Even one container loses its memory on every redeploy or restart, so an external store helps even before you scale out.
Final Thoughts
Losing user sessions after a Docker redeploy is not a mystery bug. It is the predictable result of keeping important state inside something designed to be thrown away. Replace the in-memory store with a shared, persistent one, keep your signing secret stable, shut down gracefully, and give Redis a volume and health check. Then extend the same thinking to every other piece of state your application holds.
Make the change in a staging environment first, run the kill test, and only then roll it out to production. Your users will notice only that, for once, they stayed signed in.
If you work with browser APIs and want more practical guides, browse the rest of the TVerge Tech blog and try the free developer tools.
3MutationObserver Guide: Detect DOM Changes in JS & React