Why Your Application Should Never Store Files Locally

Files written to a container's disk vanish on the next deploy, exist on only one replica and break autoscaling. Why local file storage fails in the cloud, where uploads, sessions and logs belong instead, and how to move an app's files to an S3 bucket without losing any.

Marei Morsy··12 min read
Why your app should never store files locally: two app replicas, one with the file and one answering 404, and an S3 bucket shared by both
On this page

Key takeaways

  • A container's disk is thrown away on every deploy, restart, scaling event and node change, and its files go with it.
  • With two or more replicas, a file written by one replica is invisible to the others, so uploads 404 at random.
  • Local files block autoscaling, self-healing and zero downtime deploys, and can fill the node's disk.
  • Put uploads and generated files in an S3 bucket, sessions and cache in Redis, records in a database, logs on stdout.
  • Store the object key in the database and build public or presigned URLs when you need them.
  • /tmp is fine for scratch files used within one request.

A user uploads a profile picture. It shows up, everything works. The next morning you ship a small fix, and every profile picture uploaded since the last deploy is gone. Or stranger: nothing is gone, but half your users see a broken image, the other half see the picture, and refreshing the page flips between the two.

Both bugs have the same cause. The application wrote a file to its own disk. On a laptop, or on one long-lived server, that works. On any modern platform, where your app runs in containers that are created, copied and thrown away all day, the local disk is the worst place to keep anything you want to see again.

This article explains why, where each kind of file belongs instead, and how to move an existing app's files to object storage without losing any. The examples use Cloider, but everything here applies to any container platform, Kubernetes cluster or autoscaling group.

What "local" means in a container

When a container starts, it gets a fresh filesystem: the layers of its image, read only, with a thin writable layer on top. Everything your app writes, an upload in public/uploads, a generated PDF in storage/, a SQLite file, a log file, lands in that writable layer. The layer belongs to that one container, and when the container is replaced, the layer is deleted with it.

Containers are replaced all the time:

  • On every deploy. A new version runs in new containers built from the new image. The old ones, and every file they wrote, are removed once the new ones are healthy.

  • On every restart. Changing an environment variable, a crash, an out of memory kill or a failing health check starts a new container from the image, not from where the old one left off.

  • On every scaling event. Autoscaling adds replicas with empty disks under load, and removes replicas, files included, when traffic drops.

  • On every server change. When a node is drained for maintenance or fails, its containers start again on another node, from the image.

So the question is never whether files on the local disk will disappear. It is when.

Problem 1: files disappear on every deploy

This is the one most teams hit first, usually in production, usually a few days after launch. Nothing in development warns you: your laptop's disk persists between runs, so storage/app/uploads keeps growing and everything looks fine.

In production, the app writes the upload into the container, saves its path in the database and serves it from disk. Until the next deploy. The database still points at uploads/7f3c.jpg, the new container has never heard of it, and every one of those rows is now a broken link. The loss is silent. Nothing fails at deploy time, the 404s come later, and the files are in no backup because they never left the container.

Problem 2: every replica has its own disk

Run more than one replica, which you should for availability, and the bug gets stranger. A load balancer spreads requests across the replicas, and each replica has its own private filesystem:

  1. POST /avatar reaches replica A. It writes /app/uploads/42.jpg to its own disk and stores the path in the database.

  2. GET /uploads/42.jpg reaches replica B. It looks on its own disk, finds nothing and answers 404.

  3. The user refreshes, replica A answers, and the picture is back.

With two replicas the picture shows about half the time, with four about a quarter of the time. It looks like a caching bug or a flaky network, and it is neither.

The usual band-aid is sticky sessions, which pin each user to one replica. That hides the problem from the person who uploaded the file, but everyone else still lands on other replicas, the files still vanish on the next deploy, and when that one replica goes away every file on it goes too.

The same goes for anything else a replica keeps to itself: sessions stored in memory or in files, a file based cache, a SQLite database. Cloider's scaling docs put the rule in one line: because any replica can answer any request, keep what they share outside of them. On Cloider a new app starts with 2 to 5 replicas, so this bug shows up on the first day rather than after the first traffic spike.

Problem 3: local files break scaling and self-healing

The best parts of running on a platform all assume that containers are interchangeable: adding replicas under load, replacing a broken one automatically, deploying with no downtime by starting new containers before stopping the old ones. A container that holds the only copy of some files is not interchangeable. You can't remove it without losing data, you can't add another one that sees the same files, and you can't move it to a healthier server.

Teams in that spot end up running a single replica forever and are afraid to touch it. That is a single point of failure with extra steps.

Problem 4: the disk fills up and takes the app down

A container's writable layer lives on the node's disk, next to every other container's, and it is neither big nor reserved for you. Uploads, exports and log files grow until something gives. Kubernetes evicts a pod that uses more ephemeral storage than it is allowed, and a node running out of disk starts evicting pods on its own. Either way the app restarts, and the files that filled the disk are gone with it.

Log files are the classic case. Write logs to stdout and stderr, never to app.log. The platform collects the output of every replica (on Cloider, the app's Logs tab and cloider app logs), while a log file on disk only exists until its container is replaced.

Problem 5: no durability, no backups, no history

Even a disk that lived forever would be one copy on one machine. Disks fail, servers are rebuilt, someone runs the wrong rm. Backups of container filesystems are rarely set up, and restoring one into a running fleet is harder still.

Object storage is built for this. A bucket keeps your files away from any one container or server, and the safety nets come with it instead of being scripts you have to write: versioning keeps the previous version of every overwritten or deleted file, and lifecycle rules delete temporary exports after a week or keep 90 days of history.

Problem 6: serving files through your app is slow and expensive

When files live on the app's disk, the app has to serve them: every image, video and download ties up a worker that could be answering a real request, and a 2 GB upload has to stream through your web server before it lands anywhere. Object storage serves files by URL on its own. Public files get a plain link, and private ones a short lived signed link, so the bytes go straight between the browser and the bucket and your app only hands out URLs.

What about persistent volumes?

A persistent volume survives restarts, so it fixes problem 1. It doesn't fix the others. Most volumes are ReadWriteOnce: they attach to one node at a time, which ties you to a single replica (or to one volume per replica, each with different files), slows every deploy while the volume detaches from the old pod and attaches to the new one, and still leaves you with one copy to back up. Shared ReadWriteMany filesystems such as NFS let several replicas mount the same files, but they are slower, file locking across machines is fragile, and you are still serving every byte through your app.

Volumes have their place: databases, queues and other stateful services run on them, managed by people whose job is to keep that state safe. That is what managed databases are for. For files your application creates or receives, a bucket is simpler, cheaper and scales without you. Cloider App Engine gives apps no disk that outlives a replica, on purpose.

Where each kind of data belongs

Data

Put it in

Why

User uploads (avatars, attachments, media)

An object storage bucket

Every replica sees them, they survive deploys, served by URL

Generated files (invoices, exports, reports)

A bucket, often with a lifecycle rule

Shared, durable, temporary ones expire on their own

Records and relations

A managed database

Transactions, backups, point in time recovery

Sessions

Redis or the database

Any replica can read any session

Cache

Redis

Shared, and losing it is harmless

Logs

stdout and stderr

The platform collects every replica's output

Configuration and secrets

Environment variables

Set once per environment, never baked into the image

Compiled CSS, JS and images of the app itself

The image, or a bucket behind a CDN

They change with the code, so they ship with it

Scratch files used within one request

/tmp

Fine, as long as nothing needs them afterwards

How to move file uploads to object storage

The change is smaller than it sounds. You create a bucket, give the app a key, and swap the code that writes to disk for a call to the S3 API, which almost every language and framework already supports.

1. Create a bucket and an access key. In the Cloider dashboard, open Buckets, create a bucket, then create an access key scoped to it. With the cloider CLI, the key goes straight into the app as secret environment variables:

Bash
cloider bucket create acme-uploads --wait

cloider bucket key create --label web-production --bucket acme-uploads --print-env \
  | cloider app env import web - --secret

cloider app env set web \
  S3_BUCKET=acme-uploads \
  AWS_REQUEST_CHECKSUM_CALCULATION=when_required \
  AWS_RESPONSE_CHECKSUM_VALIDATION=when_required

The app now has AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ENDPOINT_URL and AWS_REGION, which every AWS SDK reads on its own. The secret key is stored as a secret variable and never shown again.

2. Write to the bucket instead of the disk. Here is a typical Node.js upload handler that saves to disk:

JavaScript
// Before: the file lives on this replica's disk until the next deploy
const upload = multer({ dest: "uploads/" });

app.post("/avatar", upload.single("avatar"), async (req, res) => {
  await db.users.update(req.user.id, { avatar: req.file.path });
  res.sendStatus(204);
});

And the same handler writing to the bucket:

JavaScript
import { randomUUID } from "node:crypto";
import multer from "multer";
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";

const s3 = new S3Client({}); // reads AWS_* from the environment
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 5 * 1024 * 1024 } });

app.post("/avatar", upload.single("avatar"), async (req, res) => {
  const key = `avatars/${req.user.id}/${randomUUID()}`;
  await s3.send(new PutObjectCommand({
    Bucket: process.env.S3_BUCKET,
    Key: key,
    Body: req.file.buffer,
    ContentType: req.file.mimetype,
  }));
  await db.users.update(req.user.id, { avatarKey: key });
  res.sendStatus(204);
});

In Laravel the code often doesn't change at all. $request->file('avatar')->store('avatars') writes to the default disk, so pointing the default disk at the bucket moves every upload there. Install the S3 adapter with composer require league/flysystem-aws-s3-v3 "^3.0" and set:

Bash
FILESYSTEM_DISK=s3
AWS_DEFAULT_REGION=eu-central-2
AWS_BUCKET=acme-uploads
AWS_ENDPOINT=https://s3.eu-central-2.cloider.com
AWS_URL=https://acme-uploads.s3.eu-central-2.cloider.com
AWS_USE_PATH_STYLE_ENDPOINT=false

Django does the same with django-storages, and Rails with Active Storage's S3 service. The SDK guide has the configuration for each, plus complete examples in JavaScript, Python, Go, PHP, Java, Ruby and .NET.

Store the key, not the URL

Save the object's key in the database (avatars/42/9b1e0c7a-...), not a full URL and not a file path. Build the URL when you need it. That keeps you free to change the bucket, put a CDN or a custom domain in front, or switch a bucket from public to private without rewriting a single row.

For a public bucket, the URL is the bucket's address plus the key. For private files, such as invoices or anything a user paid for, hand out a presigned URL: a normal link with a signature that works for a limited time, without an access key.

JavaScript
import { GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

const url = await getSignedUrl(
  s3,
  new GetObjectCommand({ Bucket: process.env.S3_BUCKET, Key: user.avatarKey }),
  { expiresIn: 3600 }, // one hour
);

In Laravel, Storage::url($path) gives the public URL and Storage::temporaryUrl($path, now()->addHour()) a presigned one.

Let browsers upload straight to the bucket

For large files, skip your server entirely. Your app checks that the user may upload, creates a presigned PUT URL for one key and content type, and the browser sends the file to it. Your app never holds the bytes, a slow upload ties up no worker, and the size limit is the bucket's, not your web server's. The presigned URL guide has a complete server and browser example.

Browsers need CORS for this. A Cloider bucket without CORS rules accepts requests from any website. Once you add rules, list your site's origin, such as https://app.example.com.

Moving the files you already have

If your app has been writing to disk for a while, copy the existing files before you switch, so nothing breaks in between:

  1. Deploy the new code with reads that try the bucket first and fall back to the old location, or schedule a short window.

  2. Copy the files from wherever they live now (an old server, a volume, a container you can still open a shell in) with any S3 tool.

  3. Rewrite the stored paths into keys, so /app/storage/app/public/avatars/42.jpg becomes avatars/42.jpg.

  4. Run the copy once more to catch files uploaded during the move, then remove the fallback.

With the AWS CLI, the copy is one command:

Bash
export AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=...
export AWS_REQUEST_CHECKSUM_CALCULATION=when_required
export AWS_RESPONSE_CHECKSUM_VALIDATION=when_required

aws s3 sync ./storage/app/public s3://acme-uploads/ \
  --endpoint-url https://s3.eu-central-2.cloider.com --region eu-central-2

aws s3 sync only copies what is missing or changed, so running it twice is cheap. rclone works the same way if you prefer it.

When local disk is fine

Not every write to disk is a bug. These are safe:

  • Scratch files within one request, such as resizing an image in /tmp before uploading the result. Delete them when you are done.

  • Caches you can rebuild, as long as each replica having its own copy is acceptable.

  • Files baked into the image at build time, such as compiled assets, templates and fonts. They are read only, identical on every replica and ship with each deploy.

The test is simple: if losing the file on the next deploy would be a bug, it doesn't belong on the local disk.

A checklist before your next deploy

  • Search the code for writes to disk: fs.writeFile, multer({ dest }), file_put_contents, move_uploaded_file, open(path, "w"), os.Create, Laravel's local and public disks.

  • Run two replicas in staging, upload a file and load it ten times. If it ever 404s, something is still local.

  • Redeploy staging and check that every upload from before the deploy still loads.

  • Send logs to stdout and keep sessions and cache in Redis or the database.

  • Store object keys, not URLs or paths, and use presigned URLs for private files.

  • Give each app and environment its own access key, scoped to its own bucket.

Files in buckets, apps without state

An app that keeps nothing on its own disk can be deployed, restarted, scaled from 2 replicas to 100 and moved between servers without anyone noticing. That is the whole point of running on a platform.

Cloider Object Storage gives you S3 compatible buckets with versioning, lifecycle rules, CORS, presigned URLs and static websites, and Cloider App Engine runs your app with replicas, autoscaling and zero downtime deploys. Start with using buckets from apps and clusters, or create a free account and try it with the welcome credit.

Frequently asked questions

Can I store uploaded files on my server's disk?

Only if the app runs on one server that is never replaced. In containers the disk is deleted on every deploy, restart and scaling event, and each replica has its own, so store uploads in an object storage bucket and keep the object key in your database.

What happens to files inside a Docker container when it is restarted or redeployed?

Files written to a container's writable layer belong to that container. When it is replaced, on a deploy, a crash, an environment variable change or a move to another node, the new container starts from the image and the files are gone.

Why do uploaded images only show some of the time?

The app runs more than one replica and saves uploads to its local disk. The upload lands on one replica, and later requests reach others that don't have the file. Store uploads in a shared bucket instead.

Is a persistent volume a good place for user uploads?

Usually not. Most volumes attach to one node at a time, which ties the app to one replica and slows deploys, and shared NFS volumes are slower with fragile file locking. Volumes suit databases, uploads belong in object storage.

Is it safe to write to /tmp in a container?

Yes, for scratch files used within one request, such as resizing an image before uploading it. Don't rely on them afterwards: the next request can reach another replica, and /tmp is gone when the container is replaced.

How do I connect a Cloider app to a bucket?

Create an access key for the bucket and set it as the app's environment variables, with the secret key as a secret. With the CLI: cloider bucket key create --bucket <name> --print-env | cloider app env import <app> - --secret. Every AWS SDK then reads the credentials, region and endpoint on its own.

Written byMarei Morsy

Comments