Square CloudSquare Cloud

Uploaded files disappear after a deploy: ephemeral disks explained

The files disappear because they were written to the container's filesystem, which many platforms recreate on every deploy or restart. The fix is to keep user uploads in object storage and save only each file's key in the database.

Updated 7 min read

Learning objectives

After reading this article you will be able to:

  • Understand what an ephemeral disk is and why it deletes uploads without an error
  • Confirm whether the cause is an ephemeral disk, multiple instances or the deploy itself
  • Move uploads to object storage without losing the files that already exist
On this page

The upload works. Users change their profile picture, you see the files in the uploads folder, and everything is fine until the next deploy. After it, the pictures return 404. Or worse: only half of them vanish, and only sometimes.

The code did not change and nothing threw an error. What changed was where the file lived: a disk the platform treats as disposable. Understanding that rule explains the symptom and points to the fix, which is almost always to take uploads off the application's disk.

Why do files disappear after a deploy?#

An ephemeral disk is a filesystem that exists only as long as its container does: it works like any other while the process runs and is thrown away along with the container.

Many hosting platforms run applications in containers. A container starts from an image, which is read-only, and gets a writable layer on top where everything the process writes goes. Docker's documentation is blunt: by default, files created inside a container are stored on that layer, and data written to it does not persist when the container is destroyed.

On many platforms, each deploy builds a new image and starts a new container from it. The old container is thrown away along with its writable layer, and the uploads go with it. The same thing happens at other moments:

  • Restart after a failure. Kubernetes' documentation describes it: when a container crashes or is stopped, its state is not saved, every file created or modified during its lifetime is lost and the container comes back with a clean state.
  • Server move. If the platform moves the container to another machine, it starts from scratch.
  • Serverless functions. A function's /tmp is temporary and unique to each execution environment. Another environment, on the next invocation, does not see it.

Nothing fails at upload time, which is why the problem only shows up days later. The Twelve-Factor App recommends treating that disk as a brief, single-transaction cache and keeping anything that must last in an external service.

Not every platform works this way. Some keep the disk across restarts and deploys. Your provider's documentation should say what survives a restart, a redeploy and a server move.

What are the causes, from most to least common?#

  1. Ephemeral disk. The case above: a deploy, restart or server move recreates the container and wipes the writable layer.
  2. Multiple instances. With two copies of the app behind a load balancer, each one has its own disk. The upload lands on instance A and the next request hits B, which returns 404. The symptom is "it vanishes sometimes". When an instance is shut down, its files go with it.
  3. The deploy replaces the folder. Even on a persistent disk, the deploy process can overwrite the uploads folder: an rsync --delete that mirrors the repository, a package that carries the uploads folder from your laptop, or uploads written inside the build folder (dist/, build/), which is recreated on every build.
  4. Volume mounted at one path, app writing to another. The volume exists, but the code writes to ./uploads, relative to the working directory, and that path is not the volume's. The files land on the writable layer and nobody notices.
  5. Automatic cleanup. A scheduled job, an expiry rule or the system itself clearing /tmp deletes what was there.

How do you confirm it is an ephemeral disk?#

Start with the simplest test: write a marker, trigger a restart or a deploy and check whether it survived.

bash
echo "marker $(date -u)" > uploads/.marker
# restart or deploy, then, in the new process:
ls -la uploads/
cat uploads/.marker
Test result Likely cause
The marker vanished on a plain restart Ephemeral disk (cause 1)
It survived the restart and vanished on deploy A new container on every deploy (cause 1) or a deploy that overwrites the folder (cause 3)
It survived both Multiple instances (cause 2), the wrong path (cause 4) or a cleanup (cause 5)

The mount check below and the platform's docs tell causes 1 and 3 apart.

To see what is mounted at the uploads path, from inside the container:

bash
df -h "$(pwd)/uploads"   # the mount that holds the uploads
df -h /                  # the container's root, for comparison

In Docker containers, the root usually shows up with the overlay filesystem. If the uploads path sits on that same mount, and not on a separate volume, it lives on the writable layer.

For causes 2 and 4, log which instance answered and the absolute path in use, at startup and on every upload:

js
import os from "node:os";
import path from "node:path";

console.log("instance:", os.hostname(), "| uploads at:", path.resolve("uploads"));

If one instance wrote the upload and the 404 came from another, you have multiple instances. If the absolute path is not the volume's, it is the wrong path.

How do you fix it with object storage?#

The lasting fix for user uploads is to take them off the application's disk. The file goes to an object storage bucket, and the database keeps only its key. That way the file survives any deploy, every instance sees it and the browser can download it straight from storage.

Example with Express, multer and the AWS SDK v3, which works with any S3-compatible storage (npm install express multer @aws-sdk/client-s3 @aws-sdk/s3-request-presigner):

js
// server.mjs
import { randomUUID } from "node:crypto";
import { GetObjectCommand, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import express from "express";
import multer from "multer";

const s3 = new S3Client({
  region: process.env.S3_REGION,
  endpoint: process.env.S3_ENDPOINT, // leave out on AWS
  forcePathStyle: process.env.S3_PATH_STYLE === "true",
  credentials: {
    accessKeyId: process.env.S3_ACCESS_KEY,
    secretAccessKey: process.env.S3_SECRET_KEY,
  },
});

const TYPES = new Set(["image/jpeg", "image/png", "image/webp"]);
// the whole file stays in memory: cap the size
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 5 * 1024 * 1024 } });
const app = express();

app.post("/avatar", upload.single("file"), async (req, res) => {
  if (!req.file || !TYPES.has(req.file.mimetype)) {
    return res.status(400).json({ error: "send a JPEG, PNG or WebP image" });
  }
  const id = randomUUID();
  await s3.send(
    new PutObjectCommand({
      Bucket: process.env.S3_BUCKET,
      Key: `avatars/${id}`,
      Body: req.file.buffer,
      ContentType: req.file.mimetype,
    }),
  );
  res.status(201).json({ id }); // store the id on the user record, not a disk path
});

app.get("/avatar/:id", async (req, res) => {
  // check here that the requester may see the file
  const url = await getSignedUrl(
    s3,
    new GetObjectCommand({ Bucket: process.env.S3_BUCKET, Key: `avatars/${req.params.id}` }),
    { expiresIn: 300 },
  );
  res.redirect(url);
});

app.listen(process.env.PORT || 3000);

The GET redirects to a short-lived presigned URL, so the file leaves storage without going through your app. For public files, such as product images, you can use the object's direct URL. For large files, it is better to have the browser upload straight to storage, also through a presigned URL; the catch there is CORS on direct uploads. The full walkthrough is in file uploads in Node.js.

How do you migrate the files that already exist?#

If the old files are still on the current disk, act before the next deploy, because it may delete them. The order matters:

  1. Ship the code that writes to the bucket first. That way no new upload lands on the disk.

  2. Copy the old files to the bucket, from inside the environment where they are:

    bash
    aws s3 sync ./uploads s3://my-bucket/uploads --endpoint-url "$S3_ENDPOINT"
  3. Update the database, swapping each local path for the matching key in the bucket.

  4. Only then switch reads to storage, and keep a fallback to the old path for a while in case a record slipped through.

If the files are already gone, there is nothing to copy: restore them from a backup, if one exists, or ask users to upload them again.

When is the local disk still the right place?#

The application's disk is still useful for anything that can be rebuilt or only matters to that process: temporary processing files, caches, a bot's session folder, a SQLite database on a single instance with a persistent disk. The full comparison is in object storage vs local disk. If the question is whether to keep the image in the database or in a bucket, see images in the database vs object storage.

How to do this on Square Cloud#

On Square Cloud, the application's disk is persistent: files stay across restarts and deploys. A commit (new ZIP or push) overwrites only the files in the ZIP and keeps the rest of the disk. If an upload changed after a deploy there, check cause 3: a ZIP that carries files at the same path as the uploads replaces those files, so leave the uploads folder out of the package.

Each application, however, has its own disk, and one application cannot read another's files, even in the same account. With load balancing, where two or more applications serve the same custom domain, they do not share files: that is cause 2 in this article. That is why user uploads are a better fit for Blob Storage, the platform's object storage, with an S3-compatible API.

In the code above, set S3_ENDPOINT=https://s3-blob.squarecloud.app, S3_REGION=auto, S3_PATH_STYLE=true and S3_BUCKET=private, with S3 keys created in the "S3 access" tab of the dashboard; the public bucket is for open files, such as product images. Public files are served through a global edge CDN, and private ones open through a signed URL, like the one in the example, or a revocable share link of up to 30 days. Each file can be up to 10 GB, there is no egress or ingress fee, and every plan includes a storage quota. See the details on the Blob Storage page.

Blob Storage

S3-compatible object storage with no egress fees

Object storage

FAQs

Why do files disappear only sometimes, not on every deploy?

Some environments only recreate the container when it moves to another server, restarts after a failure or gets an update. If you run several instances, a file also seems to vanish when the request lands on an instance that does not have it.

Does a persistent volume fix it?

It fixes the loss on restart when there is a single instance. With two or more, each one sees its own disk unless the volume is shared, and many volume types attach to one machine at a time. For user uploads, object storage avoids both problems.

Can I store the images in the database itself?

You can, in binary columns, but the database grows fast, backups get heavy and every image served goes through your app. The common pattern is the file in object storage and its key in the database.

Is /tmp a good place for uploads?

Only as scratch space, to process a file before sending it to its final destination. In serverless functions, for example, /tmp belongs to one execution environment and is not guaranteed to exist on the next invocation.

Next articleHow much does object storage cost? Storage, requests and egressObject storage cost adds up three lines: GB stored, requests and data egress. See how each line is billed, a full worked example and the hidden costs.

More in Storage

See all 24 articles