Managing system resources proactively is essential for server stability. Whether you’re running apps as system services or using containers, you can configure automatic CPU and memory limits using either systemd or Docker.
This guide covers both methods so you can choose the one that fits your setup.
Option 1: Set Resource Limits Using systemd
If your service runs as a systemd unit (e.g., a web server, custom app, or script), you can control its resource usage directly from the unit file.
Step 1: Locate or Create the systemd Unit File
Example: For a custom script or app, create a unit file:
nano /etc/systemd/system/myapp.service
Example contents:
[Unit]
Description=My Custom App
[Service]
ExecStart=/usr/bin/myapp
Restart=always
# Resource limits
MemoryLimit=256M
CPUQuota=30%
[Install]
WantedBy=multi-user.target
• MemoryLimit – sets the max memory usage
• CPUQuota – limits CPU usage (e.g., 30% = 0.3 cores)
Step 2: Reload and Start the Service
systemctl daemon-reexec
systemctl daemon-reload
systemctl enable myapp
systemctl start myapp
Step 3: Verify the Limits
You can confirm the limits are active using:
systemctl status myapp
Or by checking resource usage with:
systemd-cgls
systemd-cgtop
Option 2: Limit Resources Using Docker
Docker allows you to isolate applications with built-in CPU and memory limits.
Step 1: Run a Docker Container with Limits
Example:
docker run -d \
--name=mycontainer \
--memory=512m \
--cpus="1.0" \
myimage
• --memory=512m – limits RAM usage
• --cpus="1.0" – limits CPU to 1 core (or use fractional values like 0.5)
Step 2: Monitor Container Resource Usage
Use the Docker stats command:
docker stats
This shows live CPU and memory usage for all running containers.
Option 3: Combine systemd with Docker
You can also run Docker containers as systemd services with enforced limits.
Example unit file:
[Unit]
Description=My Dockerized App
[Service]
ExecStart=/usr/bin/docker run --rm \
--memory=256m \
--cpus=0.5 \
myimage
Restart=always
[Install]
WantedBy=multi-user.target
Best Practices
• Always test resource limits in a staging environment
• Avoid setting limits too low, or services may crash unexpectedly
• Use monitoring tools (htop, docker stats, systemd-cgtop) to tune limits
Conclusion
Whether you’re using systemd or Docker, you can enforce automatic resource control to protect your VPS from overload. These methods offer fine-grained control over CPU and memory usage without third-party tools.
For help configuring custom services or containers, contact Hosteons Support or access your server via https://vps.hosteons.com.