How to Fix Docker Out of Memory (OOM) on DigitalOcean Droplet


As a Senior DevOps Engineer at WebToolsWiz.com, I’ve seen countless “Docker Out of Memory (OOM)” issues on DigitalOcean Droplets. Here’s a direct, actionable guide to fix it.


Fixing Docker Out of Memory (OOM) on DigitalOcean Droplets

1. The Root Cause

DigitalOcean Droplets, particularly smaller instances, have finite RAM. Docker containers, when not properly resource-limited, can exhaust the Droplet’s available memory, triggering the Linux kernel’s Out Of Memory (OOM) killer to terminate processes, including critical Docker containers.

2. Quick Fix (CLI)

Execute these commands to immediately alleviate memory pressure.

First, identify the memory hogs:

docker stats --no-stream

Next, stop any non-essential, high-memory-consuming containers:

docker stop <container_id_or_name>

Clean up unused Docker objects (stopped containers, images, volumes, networks) to free up space and memory:

docker system prune -a

Restart the Docker daemon to clear cached memory and reset any lingering issues:

sudo systemctl restart docker

3. Configuration Check

To prevent future OOM errors, impose memory limits on your Docker containers. This is best done in your docker-compose.yml file or directly in your docker run commands.

Edit your docker-compose.yml (or the relevant Docker run script) to include mem_limit and memswap_limit under the resources section for each service. Replace 512m and 1g with appropriate values for your application, ensuring the memswap_limit is equal to or greater than mem_limit.

version: '3.8'
services:
  your-app:
    image: your-image:latest
    ports:
      - "80:80"
    deploy:
      resources:
        limits:
          memory: 512m       # Sets a hard memory limit of 512MB
          # cpus: '0.5'      # (Optional) Limit CPU usage to 50% of one core
        reservations:
          memory: 256m       # (Optional) Guarantees 256MB for the container
    mem_limit: 512m          # Legacy but still widely used for runtime limits
    memswap_limit: 1g        # Total memory (RAM + swap) limit to 1GB
    # (Optional) Restart policy to automatically restart if it crashes
    restart: unless-stopped 

Apply the changes by recreating your containers:

docker-compose up -d --build --force-recreate

For docker run commands, add the --memory and --memory-swap flags:

docker run -d --memory="512m" --memory-swap="1g" --name your-app your-image:latest

4. Verification

Monitor your Droplet’s overall memory usage and your containers’ specific memory consumption.

Check overall system memory:

free -h

Monitor Docker container memory usage in real-time (press Ctrl+C to exit):

docker stats

Review system logs for any OOM killer messages. If the OOM killer was invoked recently, it will be logged here:

dmesg | grep -i oom

Ensure your containers are running stably within their new memory limits.