Prompt
How do I keep uploaded files persistent when containers restart?
Latest observation
To keep uploaded files persistent when a container restarts, you need to store them outside the container’s writable filesystem. Containers are ephemeral: if the container is recreated, any files stored only inside it are usually lost.
Common approaches
1. Use a mounted volume
Mount a host directory or managed volume into the container at the path where uploads are saved.
Example with Docker:
docker run -d \
-v /host/uploads:/app/uploads \
my-image
Then save uploads to /app/uploads inside the container.
If the container restarts, the files remain on the host volume.
2. Use named Docker volumes
Docker-managed volumes are often easier than host bind mounts.
docker volume create uploads_data
docker run -d \
-v uploads_data:/app/uploads \
my-image
This persists data across container restarts and recreations.
3. In Kubernetes, use PersistentVolumes
If you're running in Kubernetes, use a PersistentVolumeClaim and mount it into the pod.
Example conceptually:
volumeMounts:
- mountPath: /app/uploads
name: uploads-volume
volumes:
- name: uploads-volume
persistentVolumeClaim:
claimName: uploads-pvc
4. Store files in external storage
For scalable applications, store uploads in:
- Amazon S3
- Google Cloud Storage
- Azure Blob Storage
- MinIO
This is often the best option if you have multiple app instances or need durability beyond a single machine.
Best practice
- If you just need persistence on one server: use a volume
- If you need scalability or multi-instance access: use object storage
- Avoid storing uploads only inside the container filesystem
Important note
If your app writes uploads to /tmp or a local directory inside the image, those files will disappear when the container is replaced unless that directory is mounted to persistent storage.
If you want, I can show you how to do this for:
- Docker Compose
- Kubernetes
- a specific framework like Node.js, Django, Flask, or Laravel