Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › containers

How to Set Docker Container Restart Policies and Resource Limits

By Freedom251 Team · · 9 min read

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

Set a restart policy and resource limits when you create a container, or change them later with docker update. A practical starting point is:

docker run -d 
  --name app 
  --restart unless-stopped 
  --memory 512m 
  --memory-reservation 384m 
  --cpus 1.5 
  example-image:tag

This example keeps the container running unless you stop it, sets a 512 MB hard memory ceiling, requests a 384 MB soft reservation under memory pressure, and caps CPU use at 1.5 CPUs. Those numbers are examples, not universal sizing recommendations; choose them from observed workload demand and the capacity of the host.

As an Amazon Associate I earn from qualifying purchases.

What Docker restart policies and resource limits control

Docker separates two decisions:

  • Restart policy: what Docker should do when a container exits or when the Docker daemon starts again.
  • Resource limits: how much memory and CPU the container may consume on its host.

Docker’s documentation describes restart policies as controlling whether containers start automatically after they exit or when Docker restarts. By default, a container has no resource constraints and can use as much of a resource as the host kernel scheduler allows. See Docker’s restart-policy documentation and the resource-constraints guide.

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

These controls apply to Docker Engine containers. Swarm services have separate restart configuration, and behavior can vary with the Engine version, operating system, Docker Desktop environment, and kernel capabilities. Check the documentation for the exact Engine release you operate before depending on a version-sensitive option.

#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.

Choose the restart policy that matches the failure you want to handle

Setting What it does Use it when
--restart no No automatic restart; this is the default. Restart handling belongs to another system, or you deliberately want the container to stay stopped after exit.
--restart on-failure[:N] Restarts only after a non-zero exit. The optional N limits restart attempts. A failed process should be retried, but a clean exit should remain stopped.
--restart always Restarts the container whenever it stops, including after a daemon restart, subject to Docker’s manual-stop behavior. You want broad automatic recovery for a continuously running service.
--restart unless-stopped Behaves like always while retaining an explicit manual stop across a Docker daemon restart. A manually managed service should come back after host or daemon recovery, but remain stopped when an operator intentionally stopped it.

State the intent rather than selecting a policy by habit. A batch-style process that should retry failures may fit on-failure:3; a long-running service that should recover from host maintenance may fit unless-stopped; a debugging container may be better left at no.

Restart-policy behavior that commonly surprises operators

The policy is not active immediately

Docker applies a restart policy only after the container has started successfully. Docker defines successful startup for this purpose as running for at least 10 seconds. A process that dies during a short initialization window may therefore stop without the repeated restarts you expected.

on-failure does not react to a daemon restart by itself

on-failure is tied to a non-zero container exit. It does not restart a stopped container merely because the Docker daemon restarted. If daemon or host recovery is part of the requirement, evaluate always or unless-stopped instead.

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

Manual stops suppress policy-driven restarts

When you manually stop a container, Docker suppresses the policy-driven restart until the daemon restarts or you manually restart the container. The unless-stopped policy additionally remembers the manual stop across a daemon restart, so the container remains stopped until you explicitly start it.

Do not layer competing process supervisors casually

Docker warns that combining a Docker restart policy with a host-level process manager can create conflicts. Decide which layer owns restart responsibility and configure one authoritative mechanism. A restart policy is also different from --live-restore: live restore addresses daemon upgrades and is not a replacement for a container restart policy. See Docker’s explanation of automatic container starts.

Create a container with restart and resource settings

Put the options before the image name in docker run. The following complete command creates a detached container named app:

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.
docker run -d 
  --name app 
  --restart unless-stopped 
  --memory 512m 
  --memory-reservation 384m 
  --cpus 1.5 
  example-image:tag

Here, unless-stopped expresses the restart intent, --memory 512m establishes a hard maximum of 512 MB, --memory-reservation 384m supplies a lower soft threshold used under contention, and --cpus 1.5 imposes a CPU quota equivalent to up to one and a half CPUs. Replace example-image:tag with the image and tag you actually deploy.

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

Do not copy these values blindly. A hard limit that is too low can make a healthy application fail, while a limit that is too high can allow one container to crowd out other workloads. Docker warns that host memory exhaustion can cause the kernel to kill processes, including Docker or other important host processes. Size limits from measurements and leave headroom for the operating system and neighboring services.

Change a restart policy on an existing container

Use docker update instead of recreating the container when you only need to change its restart behavior:

docker update --restart unless-stopped app

The change targets the existing container named app. A policy change does not redesign the application’s failure handling: verify whether the process exits with code zero or non-zero, whether it can recover safely after a retry, and whether a manually stopped container should remain stopped after daemon recovery.

Change resource settings on an existing container

Docker also provides docker update for changing resource settings. For example:

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.
docker update --memory 768m --cpus 2 app

Use the current docker container update reference to confirm the exact option syntax, supported combinations, and constraints for your installed Engine version. Apply changes deliberately: raising a limit may protect the application but reduce capacity available to other containers, while lowering one can trigger allocation failures or out-of-memory handling.

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

Set memory limits correctly

--memory: the hard ceiling

--memory sets the container’s hard memory maximum. Docker documents a minimum value of 6 MB. Once a container reaches its configured limit, allocations can fail and the kernel’s out-of-memory mechanisms may terminate processes. Treat this as a protection boundary, not as a target amount of memory the application is guaranteed to receive.

--memory-reservation: a soft limit under contention

--memory-reservation is a soft limit that becomes relevant when the host is under memory pressure. It does not guarantee that the container stays below that amount. If you configure both values, set the reservation below the hard maximum, as in the 384 MB reservation and 512 MB ceiling in the example command.

A reservation is useful for expressing expected operating demand while retaining a higher emergency ceiling. It should not be used as a substitute for a hard cap, capacity planning, or application-level memory controls.

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

--memory-swap: combined RAM plus swap

--memory-swap controls the combined allowance of memory and swap, and it only has an effect when --memory is also set. The result depends on whether the host has swap enabled and on kernel support. A configured value cannot create swap that the host does not provide, so inspect the host’s swap policy before treating this flag as available overflow capacity.

Memory and swap settings are easy to misread because the swap value is not an additional standalone RAM limit; it describes the combined memory-plus-swap allowance. Consult Docker’s resource-constraints documentation and the container run option reference for the behavior of the exact combination you plan to use.

Do not disable OOM killing casually

Docker advises using --oom-kill-disable only when a memory limit is also set. Disabling the kernel’s ability to kill a container process without a carefully bounded memory limit can move the failure to the host, where unrelated services or Docker itself may be affected. Establish a tested hard memory limit first, and use this option only when you understand the application’s recovery behavior.

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.

Set CPU limits and understand CPU shares

--cpus: a straightforward quota

--cpus expresses a CPU ceiling as a number of CPUs. For example, --cpus="1.5" allows the container to use up to one and a half CPUs worth of scheduled time. It limits peak consumption; it does not promise that those CPUs will always be available when the host is busy.

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

--cpu-shares: relative priority, not a reservation

--cpu-shares assigns a relative weight used when containers compete for CPU. A container with more shares receives more of the available CPU time than a container with fewer shares under contention, but shares do not cap usage, reserve a fixed fraction, or guarantee a minimum CPU allocation. Use --cpus when you need a ceiling and shares when you need relative priority among competing workloads.

Docker’s Linux implementation uses kernel control groups and the Completely Fair Scheduler. The documented default CFS period is 100,000 microseconds. Resource controls that depend on kernel features may not behave identically on every operating system or Docker Desktop configuration, so validate them on the platform where the container will run.

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

Measure before choosing limits

Docker recommends testing an application’s memory needs before production. The runtime metrics command provides a live view:

docker stats app

The output includes CPU usage, memory usage, and the configured memory limit. Use it while the application handles representative traffic, startup, scheduled jobs, cache warm-up, and expected concurrency. A single quiet snapshot cannot establish a safe limit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Run the image with a provisional limit that leaves host headroom.
  2. Exercise normal and peak workflows, including the largest expected requests and background tasks.
  3. Watch the memory usage and limit columns in docker stats over the full workload period.
  4. Look for sustained growth, sudden peaks, CPU throttling symptoms, failed allocations, or process restarts.
  5. Set the hard memory ceiling above the measured peak with an explicit margin, then retest after deployment changes.
  6. Choose a CPU ceiling that preserves capacity for the host and other services; use shares only to express priority during contention.

For production sizing, repeat the exercise after changing application versions, traffic patterns, concurrency, or host capacity. The Docker runtime-metrics documentation explains the metrics that docker stats reports.

Decision guide for common container roles

Operational intent Typical starting choice Reason to verify it
Interactive debugging --restart no Unexpected restarts can hide the original failure and interfere with investigation.
Retry a worker that fails --restart on-failure:N Confirm that non-zero exits are recoverable and that the retry cap prevents an endless crash loop.
Continuously available service --restart always or unless-stopped Choose based on whether an operator’s manual stop should survive a daemon restart.
Memory-sensitive service on a shared host A tested --memory cap, optionally paired with a lower reservation Too low a cap causes application failure; too high a cap leaves less protection for the host.
CPU-intensive workload sharing a host --cpus for a ceiling, with shares only if relative priority is needed Check throughput and latency under contention instead of assuming a quota maps to a guaranteed performance level.

Troubleshoot restart and limit problems

The container exits and does not restart

  • Check whether the process exited with code zero. on-failure responds only to non-zero exits.
  • Consider whether the container ran for at least 10 seconds; Docker does not apply the policy before successful startup reaches that threshold.
  • Check for a manual stop. Docker suppresses policy-driven restarts until a daemon or manual container restart, while unless-stopped preserves the stop across daemon restarts.
  • Confirm that the policy was actually applied with docker update or at creation time, and verify option support in your Engine release.

The container restarts repeatedly

A crash loop can indicate a bad image configuration, a dependency that is unavailable, or a memory limit that is too low. Use a bounded on-failure:N policy for retryable jobs, inspect application logs, and test initialization without an aggressive restart loop. Do not add a second host process manager to compete with Docker.

The process is killed or allocations fail

  • Compare observed usage with the hard --memory limit using docker stats.
  • Remember that --memory-reservation is not a guaranteed ceiling and cannot prevent the container from exceeding that soft value.
  • Check host memory and swap availability. A --memory-swap setting cannot provide swap absent on the host.
  • Increase the limit only after confirming that the host has capacity and that other services remain protected.

CPU performance is lower than expected

A --cpus quota can intentionally throttle a busy container once it reaches its allowance. CPU shares affect only relative distribution during contention; increasing shares does not reserve a fixed CPU fraction. Measure under realistic concurrent load and adjust the quota or workload placement accordingly.

An option behaves differently on another platform

Resource controls rely on kernel and cgroup support. Docker’s resource documentation focuses on Linux kernel behavior, and the available controls can differ across Engine versions, Docker Desktop environments, and operating systems. Validate the exact deployment target rather than assuming a Linux test transfers unchanged.

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

Operational boundaries to keep clear

Restart policies apply to individual containers. Docker documents separate restart behavior for Swarm services, so do not transfer a container command directly into a Swarm deployment model. Likewise, a restart policy is not the same as live restore during a Docker upgrade.

Finally, limits protect a host only when they are realistic and tested. Unconstrained containers may consume resources as the host scheduler permits, and host-wide out-of-memory conditions can kill critical processes. Combine container limits with workload testing, host capacity planning, and a clear owner for restart behavior.

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.

containersDevOpsDockerLinuxresource limitssystem administration

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.

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver 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.