如何在Linux(Amazon Linux AMI EC2实例)中提升Docker的CPU与内存配额?
Hey there! Let's sort out this Docker resource limitation problem on your Amazon Linux AMI EC2 instance. Exit code 137 typically means your container got killed due to out-of-memory (or sometimes CPU starvation), so adjusting how much resources Docker can access is exactly what we need to do. Here's how to handle it:
Check Current Docker Resource Limits
First, let's confirm the current constraints Docker is working with. Run this command in your EC2 terminal:
docker info | grep -E "CPUs|Total Memory"
This should show you the number of CPUs and total memory Docker is allowed to use—you’ll probably see 1 CPU here, which matches what you noticed.
Modify Docker Daemon's Global Resource Configuration
On Amazon Linux (which uses systemd to manage Docker services), we’ll edit the Docker daemon configuration file to set default resource limits.
- If the configuration file doesn’t exist, create it first:
sudo touch /etc/docker/daemon.json - Open the file with your preferred editor (like nano or vim):
sudo nano /etc/docker/daemon.json - Paste in the following JSON, adjusting the values to match your EC2 instance’s available resources (for example, if your instance has 4 cores and 8GB RAM, set
"cpus": 4and"memory": "8g"):{ "cpus": 2, "memory": "4g" }cpus: The maximum number of CPU cores Docker can use across all containers.memory: The total amount of memory Docker can allocate to containers. Use units likeb(bytes),k(kilobytes),m(megabytes), org(gigabytes).
Restart Docker to Apply Changes
After saving the configuration, we need to reload the systemd daemon and restart Docker for the changes to take effect:
sudo systemctl daemon-reload sudo systemctl restart docker
Verify the New Configuration
Run the check command again to confirm the limits are updated:
docker info | grep -E "CPUs|Total Memory"
You should now see the CPU and memory values you set.
Set Per-Container Resource Limits (Optional)
If you don’t want to change the global defaults, or need to allocate specific resources to a single container, you can pass flags directly when starting the container with docker run:
- Limit CPU cores:
docker run --cpus 2 your-container-image - Limit memory:
docker run --memory 4g your-container-image - Combine both:
docker run --cpus 2 --memory 4g your-container-image
A quick note: Make sure your EC2 instance’s hardware specs can support the limits you set. For example, if you’re on a t2.micro instance (1 core, 1GB RAM), you can’t allocate more resources than the instance itself has—you’d need to upgrade to a larger instance type first if you need more capacity.
内容的提问来源于stack exchange,提问作者Carolina

