Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk12 min

How to Automate Docker Cleanup on a Linux VPS

A practical guide to scheduling Docker cleanup without deleting rollback images or persistent data: inspect usage, choose retention, build a root-owned script, schedule it, and monitor the result.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The safest general-purpose automation is a root-owned script that runs docker system prune --force --filter 'until=168h' on a schedule. The seven-day age filter limits cleanup to objects unused for at least seven days, while Docker leaves volumes alone by default. Measure with docker system df -v before and after, and widen the policy only after you have confirmed your rollback, data-retention and build-cache requirements.

What Docker cleanup actually removes

Docker does not continuously delete every object that is no longer needed. Images, stopped containers, networks and build cache can remain on disk until an operator runs a prune command. That conservative behavior prevents an automatic job from unexpectedly removing data that a deployment may still need, but it also means a small VPS can eventually run out of space.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

docker system prune is the broad cleanup command. In its default form it can remove stopped containers, unused networks, dangling images and unused build cache. It does not remove volumes unless you explicitly request volume pruning. This distinction matters because a volume can contain a database, uploads or other persistent application data even when no container is currently attached to it.

The --all (or -a) option changes image selection. Without it, image pruning is limited to dangling images. With it, Docker can delete every image that is not referenced by any container, including images you kept locally for a fast rollback. A scheduled job should therefore begin with an age filter and the narrowest object scope that solves the disk problem.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Inspect the VPS before writing a job

Start with a point-in-time inventory. Run these commands as a user that can access the Docker daemon, normally root or a member of the Docker group:

docker system df -v
docker ps -a
docker image ls
docker volume ls

docker system df -v reports Docker’s view of image, container, local-volume and build-cache usage, including reclaimable portions where available. There is no universal amount of space that a prune operation will recover: the result depends on your images, deployment history, stopped containers, cache layers and current volume contents. Capture the output before and after each policy change rather than promising a fixed percentage or number of gigabytes.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Classify what is safe to delete

  • Stopped containers: Usually disposable after logs, exit status and rollback requirements have been checked. A stopped container can still be useful for forensic inspection or a quick restart.
  • Unused networks: Networks not connected to active containers are generally safe to remove; a compose or deployment command can recreate many of them.
  • Dangling images: Untagged intermediate images are commonly safe, but inspect unusual build workflows before deleting them.
  • Unreferenced tagged images: These are the images affected by --all. Treat them as a rollback cache, not as ordinary garbage, until your retention policy says otherwise.
  • Build cache: Reclaiming it can free substantial space, but the next build may take longer and download or compile layers again.
  • Volumes: Classify every volume by owner and data sensitivity. Never infer that an unused volume is empty or disposable from its name alone.

Choose a retention policy

A practical starting point for a small VPS is to retain unused objects for seven days, represented by the documented until=168h filter. Observe deployments and rollbacks for at least one normal operating cycle, then lengthen or shorten the window based on evidence. The right value is the longest period in which an old image, stopped container or cache layer could still be needed.

Policy Objects affected Retention control Rollback and data risk When to use it
Conservative system prune Stopped containers, unused networks, dangling images and build cache; volumes remain until and label filters Lower risk; does not remove volumes and does not delete all unreferenced images Default scheduled job on most VPSs
Broad image cleanup All images not referenced by a container, subject to filters --all plus age or label filters Can remove locally cached rollback images Hosts that can pull or rebuild images reliably and have another rollback source
Container-only prune Stopped containers until and labels Does not touch images, networks, volumes or build cache When exited containers and their writable layers are the main problem
Image-only prune Dangling images, or all unreferenced images with --all until and labels With --all, cached rollback images can disappear When image storage dominates and container cleanup is not desired
Separate build-cache policy BuildKit/buildx cache max-used-space, min-free-space and reserved-space Builds may become slower after cache eviction When build cache, rather than runtime objects, consumes the disk

Labels are useful when your deployment process applies stable labels to objects that must be kept or may be removed. Docker documents positive and negative label filters for prune commands. Prefer labels over an informal naming convention, but verify that every deployment path actually sets the labels before relying on them.

Use the conservative system-prune command

The baseline command for a scheduled job is:

/usr/bin/docker system prune --force --filter 'until=168h'

--force suppresses the interactive confirmation prompt, which is required for unattended execution. The until=168h filter limits candidates to objects unused for at least 168 hours. In this form, Docker leaves volumes out of the operation and does not broaden image deletion to every unreferenced tag.

Run it manually during a maintenance window before scheduling it:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Run docker system df -v and save the output in your change record.
  2. Run the command without --force once, so you can read Docker’s confirmation summary and verify the scope.
  3. Inspect active services with docker ps and confirm that no deployment, backup or migration is in progress.
  4. Run the forced form and then repeat docker system df -v.
  5. Check application health, recent container logs and available filesystem space.

The command is intentionally not a promise that all objects older than seven days will disappear. An object may still be referenced, connected or otherwise ineligible under Docker’s rules. Treat the filter as an age boundary for eligible objects, not as a guaranteed deletion date.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Put cleanup in a root-owned wrapper

A wrapper gives you one place to set the policy, use an absolute Docker path and produce auditable output. Create /usr/local/sbin/docker-cleanup with root ownership:

#!/bin/sh
set -eu
/usr/bin/docker system df
/usr/bin/docker system prune --force --filter 'until=168h'
/usr/bin/docker system df

Install and protect it:

sudo install -o root -g root -m 0750 /dev/stdin /usr/local/sbin/docker-cleanup <<'EOF'
#!/bin/sh
set -eu
/usr/bin/docker system df
/usr/bin/docker system prune --force --filter 'until=168h'
/usr/bin/docker system df
EOF

If your distribution does not support installing from standard input in that form, create the file with a root editor, then run sudo chown root:root /usr/local/sbin/docker-cleanup and sudo chmod 0750 /usr/local/sbin/docker-cleanup. Keep the script outside a deployer’s writable directory so a compromised application account cannot change what the scheduled job executes.

The wrapper uses the shorter system df report for logs. Use system df -v interactively when you need per-object detail. The script exits on an error because of set -eu; a failed Docker command therefore becomes visible to the scheduler instead of being mistaken for a successful cleanup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Schedule it with a systemd service and timer

On a Linux distribution that uses systemd, a service plus timer provides explicit unit status, journal logs and ordering after Docker starts. Create /etc/systemd/system/docker-cleanup.service:

[Unit]
Description=Prune eligible Docker objects
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/docker-cleanup

Create /etc/systemd/system/docker-cleanup.timer:

[Unit]
Description=Run Docker cleanup daily

[Timer]
OnCalendar=daily
Persistent=true
RandomizedDelaySec=15m
Unit=docker-cleanup.service

[Install]
WantedBy=timers.target

Enable and start the timer:

sudo systemctl daemon-reload
sudo systemctl enable --now docker-cleanup.timer

Verify both scheduling and the first run:

systemctl status docker-cleanup.timer
systemctl list-timers docker-cleanup.timer
sudo systemctl start docker-cleanup.service
sudo systemctl status docker-cleanup.service
sudo journalctl -u docker-cleanup.service --since today

Persistent=true allows a missed calendar event to run when the VPS returns after being powered off. The randomized delay prevents every host using the same daily schedule from starting at exactly the same minute. If your maintenance process requires a fixed time, remove the random delay and choose an explicit OnCalendar value instead.

The service depends on docker.service, but it does not stop containers or restart the daemon. Cleanup runs against the daemon that is already serving workloads. The timer’s journal is the primary record of command output and failures; restrict journal access according to your normal server policy because image names, paths and application details can appear in output.

Use cron when systemd is not available

Cron is adequate on systems that do not use systemd or where an existing operations standard requires it. Place a root-owned entry in /etc/cron.d/docker-cleanup:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
17 3 * * * root /usr/local/sbin/docker-cleanup >> /var/log/docker-cleanup.log 2>&1

The first five fields run the job daily at 03:17 in the server’s local cron timezone. Confirm that the VPS’s timezone and maintenance window are what you expect. Ensure the file is owned by root and has permissions accepted by your cron implementation. Rotate or constrain /var/log/docker-cleanup.log so the log itself cannot become a disk-space problem.

Cron does not provide the same built-in dependency ordering as the systemd unit. If the daemon may be unavailable at 03:17, the wrapper will fail and the redirected output will show the reason. You can then choose a later schedule, add an operational retry mechanism supported by your distribution, or move to a systemd timer.

Expand image cleanup only when rollback policy allows it

Adding --all is a policy decision, not a performance tweak:

/usr/bin/docker system prune --all --force --filter 'until=168h'

This can delete any image not referenced by a container once it passes the age filter. A container that is currently running references its image, but an image kept solely for a future rollback may not be referenced at all. Before enabling this form, document where rollback images come from, how long they must remain available and how long pulling a replacement would take during an incident.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If the goal is only to remove stopped containers, use the narrower command:

docker container prune --force --filter 'until=168h'

For image storage specifically, use:

docker image prune --all --force --filter 'until=240h'

The 240-hour value in this example is a ten-day retention boundary, not a universal recommendation. Choose it to match your image rollback window and state the duration in your runbook. Both commands support label filters; combine an age rule with labels when your deployment system can identify images or containers that are safe to remove.

Treat volumes as a separate data-governance task

Routine system pruning leaves volumes alone by design. That default protects persistent data but means volume growth will not be solved by the ordinary cleanup timer.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Anonymous volumes

To remove unused anonymous local volumes, run:

docker volume prune --force

Use this only after checking docker volume ls and confirming that anonymous volumes are not part of a recovery workflow. An anonymous volume can contain state even when its original container has been removed.

Named volumes

docker volume prune --all --force is broader and can remove unused named volumes. Do not add it to a routine job merely because the command succeeds in a test. First inventory volume names, owners, mount points and backup status; then verify that each candidate is either reproducible or covered by a tested restore procedure. Check the installed Docker CLI’s help output because option availability, including volume --all, can vary with Docker Engine and API versions.

Keep volume deletion as a separately approved task unless your infrastructure encodes ownership and retention labels reliably. A cleanup script cannot infer that a detached database volume is obsolete rather than waiting for a blue-green deployment or disaster-recovery test.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Control build cache with buildx when it is the main consumer

Runtime pruning is not always the answer. If docker system df -v shows that BuildKit cache dominates usage, use the buildx-specific prune command and bound the cache instead of deleting unrelated containers or images:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
docker buildx prune --force --max-used-space 10GB --min-free-space 5GB --reserved-space 2GB

These limits express a cache policy: cap how much cache may be used, require a minimum amount of free space and reserve space that eviction should protect. Select values from the VPS’s actual disk size and build workload; the figures above are examples, not a claim that every host should use them. Review docker buildx prune --help on the installed version before scheduling because buildx options and behavior can vary.

Cache eviction trades disk space for build time. A deployment that builds frequently may need a larger reserved cache, while a host that builds only occasionally may favor aggressive limits. Keep build-cache cleanup in its own service or script when you want to observe that trade-off independently from runtime-object cleanup.

Keep logs and filesystem capacity under control

Deleting images and stopped containers does not rotate container logs. A busy service can fill the filesystem even when Docker reports little reclaimable image space. Review the logging driver and its rotation settings using your distribution’s Docker logging documentation and apply a retention policy appropriate for compliance and incident response.

Monitor the filesystem that contains Docker’s data root, commonly the filesystem mounted at /var/lib/docker, rather than watching only the root filesystem percentage. Alert before free space becomes critical, and include inode exhaustion if your monitoring system supports it. A useful alert should identify the mount point, current free bytes or percentage, and whether the latest cleanup unit succeeded.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep cleanup output in the system journal or a root-readable log. Record the start time, exit status and before/after space reports. Do not treat a successful command exit as proof that the filesystem problem is solved; Docker may have little eligible data, or another directory such as application logs may be responsible.

Production safety checklist

  • Run the candidate command interactively on a staging VPS or during a maintenance window before enabling automation.
  • Confirm the absolute Docker binary path with command -v docker and adjust the script if your distribution installs it elsewhere.
  • Run the job with permissions that can access the Docker daemon; a scheduler’s restricted environment may not match your interactive shell.
  • Start without --all and without any volume option unless a written retention policy requires those broader scopes.
  • Use age or label filters so a newly abandoned object is not immediately deleted.
  • Keep the rollback window inside the retention period, including the time needed to identify and redeploy a previous image.
  • Verify that backups cover every persistent volume before considering named-volume pruning.
  • Check the local CLI help and matching Docker reference for option differences before rollout.
  • Inspect timer or cron logs after the first automated run and after Docker upgrades.
  • Alert on both cleanup failures and low free space; one does not substitute for the other.

Troubleshoot common outcomes

The command says there is nothing to prune

This means no objects matched the selected scope and filters at that moment. Compare docker system df -v with docker ps -a, docker image ls and docker volume ls. Large named volumes, active images, logs or a different filesystem may account for the disk usage.

Disk usage barely changes

Check whether build cache is the largest category and use a bounded buildx policy if it is. Check container log growth and application data outside Docker’s reclaimable categories. Also verify that you measured the same filesystem before and after; host-level disk usage can include deleted files still held open by a process.

A rollback image disappeared

The likely cause is an image-prune policy using --all without a long enough age or label rule. Restore the image from your registry or rebuild it, then revise the retention window so the required rollback period is covered. Do not re-enable the broad policy until the rollback procedure has been exercised.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The scheduled job works manually but fails in cron or systemd

Use absolute paths, inspect the unit journal or cron log, and verify daemon permissions. Scheduled jobs often have a smaller environment than an interactive shell. Confirm that Docker is running at the scheduled time and that the wrapper is executable and owned by root.

A volume was not removed

That is expected for the default system prune. Volumes require a separate command. If you intend to remove anonymous or named volumes, stop and perform the inventory, label, backup and restore checks first; do not add --volumes to the routine job as a quick fix.

Validate the automation over time

After enabling a timer or cron entry, review several runs rather than judging it from one execution. Compare the before/after reports, filesystem free-space trend, deployment duration and rollback availability. A policy that keeps the disk stable but forces every deployment to rebuild large layers may need a larger cache allowance. A policy that preserves rollback images but still leaves the filesystem full may need a separate log or volume-retention project.

When Docker Engine, the CLI or buildx is upgraded, rerun the local help commands and review the unit output. Command availability and option details can vary by Engine and API version, so treat an upgrade as a reason to revalidate—not as evidence that the existing policy has changed automatically.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.