Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(apps): first-class per-app CPU/memory limits

Juan Denis9edeb68f85d6
diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py
index 82157341..24454ef4 100644
--- a/backend/app/api/apps.py
+++ b/backend/app/api/apps.py
@@ -1509,6 +1509,118 @@ def sweep_idle_apps():
return jsonify(ContainerSleepService.sweep_idle())
+# ==================== RESOURCE LIMITS (task #23) ====================
+
+def _parse_docker_stats(stats):
+ """Normalize a `docker stats --format json` row to a small usage dict.
+
+ Returns None when stats are unavailable (stopped app, no Docker on the
+ host — e.g. Windows dev).
+ """
+ if not stats:
+ return None
+
+ def _pct(value):
+ try:
+ return float(str(value).rstrip('%'))
+ except (TypeError, ValueError):
+ return None
+
+ usage = {
+ 'cpu_percent': _pct(stats.get('CPUPerc')),
+ 'memory_percent': _pct(stats.get('MemPerc')),
+ 'memory_usage': None,
+ 'memory_limit': None,
+ }
+ mem = stats.get('MemUsage') or ''
+ if '/' in mem:
+ used, limit = mem.split('/', 1)
+ usage['memory_usage'] = used.strip()
+ usage['memory_limit'] = limit.strip()
+ return usage
+
+
+@apps_bp.route('/<int:app_id>/resources', methods=['GET'])
+@jwt_required()
+def get_app_resources(app_id):
+ """The app's configured CPU/memory limits plus best-effort live usage."""
+ user = User.query.get(get_jwt_identity())
+ app = Application.query.get(app_id)
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+ if not _can_access_app(user, app):
+ return jsonify({'error': 'Access denied'}), 403
+
+ usage = None
+ if app.status == 'running' and not app.server_id:
+ try:
+ container_id = DockerService.get_app_container_id(app)
+ if container_id:
+ usage = _parse_docker_stats(DockerService.get_container_stats(container_id))
+ except Exception:
+ usage = None # live stats are best-effort
+
+ return jsonify({
+ 'cpu_limit': app.cpu_limit,
+ 'memory_limit': app.memory_limit,
+ 'usage': usage,
+ }), 200
+
+
+@apps_bp.route('/<int:app_id>/resources', methods=['PUT'])
+@jwt_required()
+def update_app_resources(app_id):
+ """Set the app's CPU/memory limits; re-apply live when possible.
+
+ Empty/null clears a limit. For a locally managed compose app that is
+ running, `compose up -d` regenerates the ServerKit override (which carries
+ the limits) and recreates changed containers; otherwise the limits are
+ saved and take effect on the next restart/redeploy.
+ """
+ user = User.query.get(get_jwt_identity())
+ app = Application.query.get(app_id)
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+ if not _can_edit_app(user, app):
+ return jsonify({'error': 'Access denied'}), 403
+
+ data = request.get_json() or {}
+ try:
+ if 'cpu_limit' in data:
+ app.cpu_limit = DockerService.validate_cpu_limit(data['cpu_limit'])
+ if 'memory_limit' in data:
+ app.memory_limit = DockerService.validate_memory_limit(data['memory_limit'])
+ except ValueError as e:
+ return jsonify({'error': str(e)}), 400
+
+ db.session.commit()
+
+ applied = False
+ note = None
+ is_local_compose = (
+ not app.server_id and app.root_path
+ and (app.app_type == 'docker' or app.managed_by == 'docker_compose')
+ )
+ if app.status == 'running':
+ if is_local_compose:
+ result = DockerService.compose_up(app.root_path, compose_file=_local_compose_file(app))
+ applied = bool(result.get('success'))
+ if not applied:
+ note = 'restart required'
+ else:
+ note = 'restart required'
+
+ response = {
+ 'message': 'Resource limits saved',
+ 'cpu_limit': app.cpu_limit,
+ 'memory_limit': app.memory_limit,
+ 'applied': applied,
+ }
+ if note:
+ response['note'] = note
+ return jsonify(response), 200
+
+
@apps_bp.route('/<int:app_id>/scale-policy', methods=['GET'])
@jwt_required()
def get_scale_policy(app_id):
diff --git a/backend/app/models/application.py b/backend/app/models/application.py
index 19d50df2..6f587dd5 100644
--- a/backend/app/models/application.py
+++ b/backend/app/models/application.py
@@ -38,6 +38,11 @@ class Application(db.Model):
# Build packs (zero-Dockerfile deploys). When the build method routes through
# the build-pack layer, the detected plan and any user overrides are persisted
# here so the generated Dockerfile is reproducible and the UI can show it.
+ # Per-app resource limits (task #23). Docker-enforced caps emitted into the
+ # generated compose service block (`cpus` / `mem_limit`). NULL = unlimited.
+ cpu_limit = db.Column(db.String(16), nullable=True) # CPU cores, e.g. '1.5'
+ memory_limit = db.Column(db.String(16), nullable=True) # e.g. '512m', '2g'
+
buildpack_type = db.Column(db.String(20), nullable=True) # 'nixpacks' | 'static' | 'dockerfile-present' | 'unknown'
buildpack_plan = db.Column(db.Text, nullable=True) # JSON: the detected build plan
buildpack_overrides = db.Column(db.Text, nullable=True) # JSON: user overrides applied to the plan
@@ -110,6 +115,8 @@ class Application(db.Model):
'docker_image': self.docker_image,
'container_id': self.container_id,
'registry_id': self.registry_id,
+ 'cpu_limit': self.cpu_limit,
+ 'memory_limit': self.memory_limit,
'buildpack_type': self.buildpack_type,
'buildpack_plan': json.loads(self.buildpack_plan) if self.buildpack_plan else None,
'buildpack_overrides': json.loads(self.buildpack_overrides) if self.buildpack_overrides else None,
diff --git a/backend/app/services/compose_env_service.py b/backend/app/services/compose_env_service.py
index ac72b390..58f5f94c 100644
--- a/backend/app/services/compose_env_service.py
+++ b/backend/app/services/compose_env_service.py
@@ -97,6 +97,21 @@ class ComposeEnvService:
logger.debug('could not read services from %s: %s', base_compose_path, e)
return []
+ @staticmethod
+ def _limits_block(app):
+ """Compose keys for the app's resource limits, or {} when unset/invalid."""
+ block = {}
+ try:
+ cpu = getattr(app, 'cpu_limit', None)
+ if cpu:
+ block['cpus'] = float(cpu)
+ mem = getattr(app, 'memory_limit', None)
+ if mem:
+ block['mem_limit'] = str(mem)
+ except (TypeError, ValueError):
+ return {}
+ return block
+
@staticmethod
def _escape(value):
"""Escape a value for a compose ``environment:`` entry.
@@ -136,20 +151,25 @@ class ComposeEnvService:
# it targets a specific one (EnvironmentVariable/SharedVariable
# .target_service). Local env vars override shared variable groups.
per_service = EnvService.get_effective_env_for_services(app.id, service_names)
- if not per_service or not any(per_service.values()):
- # No effective env on any service → make sure no stale override lingers.
- cls._remove_override(project_path)
- return None
services_block = {}
for name in service_names:
- svc_env = per_service.get(name) or {}
+ svc_env = (per_service or {}).get(name) or {}
if not svc_env:
continue # nothing targeted at this service
services_block[name] = {
'environment': {k: cls._escape(v) for k, v in svc_env.items() if k}
}
+
+ # Per-app resource limits (task #23): cap the app's primary
+ # (first-declared) compose service. mem_limit/cpus apply with plain
+ # (non-swarm) docker compose.
+ limits = cls._limits_block(app)
+ if limits:
+ services_block.setdefault(service_names[0], {}).update(limits)
+
if not services_block:
+ # Nothing to inject → make sure no stale override lingers.
cls._remove_override(project_path)
return None
override = {'services': services_block}
@@ -158,7 +178,8 @@ class ComposeEnvService:
header = (
'# Managed by ServerKit — do not edit.\n'
'# Injects the app\'s effective environment (shared variable groups\n'
- '# under the app\'s own local env vars) into every compose service.\n'
+ '# under the app\'s own local env vars) into every compose service,\n'
+ '# plus any per-app resource limits on the primary service.\n'
'# Regenerated on every deploy; delete it and it will be recreated.\n'
)
with open(override_path, 'w', encoding='utf-8') as f:
diff --git a/backend/app/services/docker_service.py b/backend/app/services/docker_service.py
index 91b4d890..2743451e 100644
--- a/backend/app/services/docker_service.py
+++ b/backend/app/services/docker_service.py
@@ -1,4 +1,5 @@
import logging
+import re
import subprocess
import json
import os
@@ -8,6 +9,9 @@ from datetime import datetime
logger = logging.getLogger(__name__)
+# Docker-style memory limit: a number plus a one-letter unit (bytes/kilo/mega/giga).
+_MEMORY_LIMIT_RE = re.compile(r'^\d+(\.\d+)?(b|k|m|g)$', re.IGNORECASE)
+
class DockerService:
"""Service for managing Docker containers, images, and compose stacks."""
@@ -514,6 +518,43 @@ class DockerService:
'finished_at': state.get('FinishedAt')
}
+ # ==================== RESOURCE LIMITS (task #23) ====================
+
+ @staticmethod
+ def validate_cpu_limit(value):
+ """Normalize a CPU-cores limit ('1.5' → '1.5'). Empty/None clears it.
+
+ Returns the normalized string or None; raises ValueError when invalid.
+ """
+ if value is None:
+ return None
+ text = str(value).strip()
+ if not text:
+ return None
+ try:
+ cores = float(text)
+ except ValueError:
+ raise ValueError('CPU limit must be a number of cores, e.g. "1.5"')
+ if cores <= 0:
+ raise ValueError('CPU limit must be a positive number of cores')
+ return text
+
+ @staticmethod
+ def validate_memory_limit(value):
+ """Normalize a memory limit ('512m', '2g'). Empty/None clears it.
+
+ Returns the normalized (lowercased) string or None; raises ValueError
+ when invalid.
+ """
+ if value is None:
+ return None
+ text = str(value).strip().lower()
+ if not text:
+ return None
+ if not _MEMORY_LIMIT_RE.match(text):
+ raise ValueError('Memory limit must be a number with a unit, e.g. "512m" or "2g"')
+ return text
+
@staticmethod
def get_container_stats(container_id):
"""Get container resource usage stats."""
@@ -1179,13 +1220,16 @@ class DockerService:
@staticmethod
def create_docker_app(app_path, app_name, image, ports=None, volumes=None, env=None,
- named_volumes=None):
+ named_volumes=None, cpu_limit=None, memory_limit=None):
"""Create a Docker-based application with docker-compose.
``named_volumes`` is a list of managed Docker volume names to declare as
top-level (``external: false``) volumes — Compose requires the top-level
declaration for any named volume referenced by a service. Callers pass the
matching ``name:/mount`` specs in ``volumes`` (see AppVolume.mount_spec).
+
+ ``cpu_limit`` / ``memory_limit`` (task #23) emit ``cpus`` / ``mem_limit``
+ on the app's service block so Docker enforces the caps.
"""
try:
os.makedirs(app_path, exist_ok=True)
@@ -1211,6 +1255,12 @@ class DockerService:
if env:
compose['services'][app_name]['environment'] = env
+ if cpu_limit:
+ compose['services'][app_name]['cpus'] = float(cpu_limit)
+
+ if memory_limit:
+ compose['services'][app_name]['mem_limit'] = str(memory_limit)
+
if named_volumes:
# Top-level named volumes so a redeploy reuses the same volume
# instead of a fresh anonymous one.
diff --git a/backend/migrations/versions/048_app_resource_limits.py b/backend/migrations/versions/048_app_resource_limits.py
new file mode 100644
index 00000000..ccc2da0f
--- /dev/null
+++ b/backend/migrations/versions/048_app_resource_limits.py
@@ -0,0 +1,47 @@
+"""Per-app resource limits (task #23).
+
+Adds:
+- applications.cpu_limit (CPU cores, e.g. '1.5')
+- applications.memory_limit (e.g. '512m', '2g')
+
+Both nullable — NULL means unlimited (today's behavior). When set they are
+emitted into the app's generated compose service block (`cpus` / `mem_limit`).
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on boot
+before Alembic, so guard on the live schema.
+
+Revision ID: 048_app_resource_limits
+Revises: 047_agent_footprint_dirs
+Create Date: 2026-07-03
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '048_app_resource_limits'
+down_revision = '047_agent_footprint_dirs'
+branch_labels = None
+depends_on = None
+
+_COLUMNS = ('cpu_limit', 'memory_limit')
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'applications' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('applications')}
+ for name in _COLUMNS:
+ if name not in cols:
+ op.add_column('applications', sa.Column(name, sa.String(16), nullable=True))
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'applications' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('applications')}
+ for name in _COLUMNS:
+ if name in cols:
+ op.drop_column('applications', name)
diff --git a/backend/tests/test_app_resource_limits.py b/backend/tests/test_app_resource_limits.py
new file mode 100644
index 00000000..e5346de2
--- /dev/null
+++ b/backend/tests/test_app_resource_limits.py
@@ -0,0 +1,306 @@
+"""Per-app resource limits (task #23) — validation, model, compose gen, API.
+
+Proving points:
+- CPU/memory limit validation accepts sane values and rejects junk
+- Application round-trips cpu_limit/memory_limit and exposes them in to_dict
+- create_docker_app emits `cpus` / `mem_limit` on the app's service block
+- the ComposeEnvService override carries the limits onto the primary service
+- GET /apps/<id>/resources returns limits + best-effort usage (None when
+ Docker stats are unavailable, e.g. stopped app or Windows dev)
+- PUT /apps/<id>/resources validates, saves, and re-applies best-effort
+"""
+import os
+
+import pytest
+import yaml
+
+from app import db
+from app.models import Application, User
+from app.services.compose_env_service import ComposeEnvService
+from app.services.docker_service import DockerService
+
+
+def owner(app):
+ user = User(email='[email protected]', username='limitsowner',
+ password_hash='x', role=User.ROLE_ADMIN, is_active=True)
+ db.session.add(user)
+ db.session.commit()
+ return user
+
+
+def docker_app(app, owner):
+ application = Application(name='limits-app', app_type='docker', status='stopped',
+ root_path='/tmp/limits-app', user_id=owner.id)
+ db.session.add(application)
+ db.session.commit()
+ return application
+
+
+# ── validation ───────────────────────────────────────────────────────────────
+
+def test_cpu_limit_validation_accepts_positive_floats():
+ assert DockerService.validate_cpu_limit('1.5') == '1.5'
+ assert DockerService.validate_cpu_limit(' 2 ') == '2'
+ assert DockerService.validate_cpu_limit('0.25') == '0.25'
+
+
+def test_cpu_limit_validation_clears_on_empty():
+ assert DockerService.validate_cpu_limit(None) is None
+ assert DockerService.validate_cpu_limit('') is None
+ assert DockerService.validate_cpu_limit(' ') is None
+
+
[email protected]('bad', ['0', '-1', 'two', '1,5'])
+def test_cpu_limit_validation_rejects_junk(bad):
+ with pytest.raises(ValueError):
+ DockerService.validate_cpu_limit(bad)
+
+
+def test_memory_limit_validation_accepts_docker_units():
+ assert DockerService.validate_memory_limit('512m') == '512m'
+ assert DockerService.validate_memory_limit('2G') == '2g' # lowercased
+ assert DockerService.validate_memory_limit('1.5g') == '1.5g'
+ assert DockerService.validate_memory_limit('1024k') == '1024k'
+
+
+def test_memory_limit_validation_clears_on_empty():
+ assert DockerService.validate_memory_limit(None) is None
+ assert DockerService.validate_memory_limit('') is None
+
+
[email protected]('bad', ['512', 'm512', '2tb', 'lots', '-512m', '512mb'])
+def test_memory_limit_validation_rejects_junk(bad):
+ with pytest.raises(ValueError):
+ DockerService.validate_memory_limit(bad)
+
+
+# ── model round-trip ─────────────────────────────────────────────────────────
+
+def test_model_round_trip_and_to_dict(docker_app):
+ docker_app.cpu_limit = '1.5'
+ docker_app.memory_limit = '512m'
+ db.session.commit()
+
+ reloaded = Application.query.get(docker_app.id)
+ assert reloaded.cpu_limit == '1.5'
+ assert reloaded.memory_limit == '512m'
+
+ payload = reloaded.to_dict()
+ assert payload['cpu_limit'] == '1.5'
+ assert payload['memory_limit'] == '512m'
+
+
+def test_to_dict_defaults_limits_to_none(docker_app):
+ payload = docker_app.to_dict()
+ assert payload['cpu_limit'] is None
+ assert payload['memory_limit'] is None
+
+
+# ── compose generation ───────────────────────────────────────────────────────
+
+def test_create_docker_app_emits_limits(tmp_path):
+ app_path = str(tmp_path / 'stack')
+ result = DockerService.create_docker_app(app_path, 'web', 'nginx:latest',
+ cpu_limit='1.5', memory_limit='512m')
+ assert result['success'] is True
+
+ with open(os.path.join(app_path, 'docker-compose.yml')) as f:
+ compose = yaml.safe_load(f)
+ svc = compose['services']['web']
+ assert svc['cpus'] == 1.5
+ assert svc['mem_limit'] == '512m'
+
+
+def test_create_docker_app_omits_limits_when_unset(tmp_path):
+ app_path = str(tmp_path / 'stack')
+ result = DockerService.create_docker_app(app_path, 'web', 'nginx:latest')
+ assert result['success'] is True
+
+ with open(os.path.join(app_path, 'docker-compose.yml')) as f:
+ compose = yaml.safe_load(f)
+ svc = compose['services']['web']
+ assert 'cpus' not in svc
+ assert 'mem_limit' not in svc
+
+
+def test_compose_override_carries_limits_on_primary_service(tmp_path, docker_app, monkeypatch):
+ """A managed compose app with limits (and no env vars) still gets a
+ ServerKit override that caps the first-declared service."""
+ project = tmp_path / 'proj'
+ project.mkdir()
+ (project / 'docker-compose.yml').write_text(
+ 'services:\n web:\n image: nginx:latest\n db:\n image: mysql:8.0\n'
+ )
+ docker_app.root_path = str(project)
+ docker_app.cpu_limit = '2'
+ docker_app.memory_limit = '1g'
+ db.session.commit()
+
+ from app.services.env_service import EnvService
+ monkeypatch.setattr(EnvService, 'get_effective_env_for_services',
+ staticmethod(lambda app_id, names: {}))
+
+ override_path = ComposeEnvService.refresh_for_project(str(project))
+ assert override_path is not None
+
+ with open(override_path) as f:
+ override = yaml.safe_load(f)
+ web = override['services']['web'] # primary (first-declared) service
+ assert web['cpus'] == 2.0
+ assert web['mem_limit'] == '1g'
+ assert 'db' not in override['services'] # secondary services untouched
+
+
+def test_compose_override_removed_when_no_env_and_no_limits(tmp_path, docker_app, monkeypatch):
+ project = tmp_path / 'proj'
+ project.mkdir()
+ (project / 'docker-compose.yml').write_text('services:\n web:\n image: nginx:latest\n')
+ docker_app.root_path = str(project)
+ db.session.commit()
+
+ from app.services.env_service import EnvService
+ monkeypatch.setattr(EnvService, 'get_effective_env_for_services',
+ staticmethod(lambda app_id, names: {}))
+
+ # Pre-seed a stale override; the refresh must remove it.
+ (project / ComposeEnvService.OVERRIDE_NAME).write_text('services: {}\n')
+ assert ComposeEnvService.refresh_for_project(str(project)) is None
+ assert not os.path.exists(str(project / ComposeEnvService.OVERRIDE_NAME))
+
+
+# ── API ──────────────────────────────────────────────────────────────────────
+
+def _make_api_app(status='stopped', **kwargs):
+ owner = User.query.filter_by(username='testadmin').first()
+ application = Application(name='api-limits', app_type='docker', status=status,
+ root_path='/tmp/api-limits', user_id=owner.id, **kwargs)
+ db.session.add(application)
+ db.session.commit()
+ return application
+
+
+def test_api_get_resources_stopped_app_usage_none(client, auth_headers, app):
+ application = _make_api_app()
+ resp = client.get(f'/api/v1/apps/{application.id}/resources', headers=auth_headers)
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data == {'cpu_limit': None, 'memory_limit': None, 'usage': None}
+
+
+def test_api_get_resources_running_app_parses_stats(client, auth_headers, app, monkeypatch):
+ application = _make_api_app(status='running')
+ application.cpu_limit = '1.5'
+ application.memory_limit = '512m'
+ db.session.commit()
+
+ monkeypatch.setattr(DockerService, 'get_app_container_id',
+ classmethod(lambda cls, a: 'cid123'))
+ monkeypatch.setattr(DockerService, 'get_container_stats',
+ staticmethod(lambda cid: {
+ 'CPUPerc': '12.34%',
+ 'MemPerc': '25.00%',
+ 'MemUsage': '128MiB / 512MiB',
+ }))
+
+ resp = client.get(f'/api/v1/apps/{application.id}/resources', headers=auth_headers)
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data['cpu_limit'] == '1.5'
+ assert data['memory_limit'] == '512m'
+ assert data['usage'] == {
+ 'cpu_percent': 12.34,
+ 'memory_percent': 25.0,
+ 'memory_usage': '128MiB',
+ 'memory_limit': '512MiB',
+ }
+
+
+def test_api_get_resources_stats_failure_is_clean(client, auth_headers, app, monkeypatch):
+ """Docker unreachable (e.g. Windows dev) → usage is None, not a 500."""
+ application = _make_api_app(status='running')
+ monkeypatch.setattr(DockerService, 'get_app_container_id',
+ classmethod(lambda cls, a: (_ for _ in ()).throw(OSError('no docker'))))
+
+ resp = client.get(f'/api/v1/apps/{application.id}/resources', headers=auth_headers)
+ assert resp.status_code == 200
+ assert resp.get_json()['usage'] is None
+
+
+def test_api_put_resources_saves_stopped_app(client, auth_headers, app):
+ application = _make_api_app()
+ resp = client.put(f'/api/v1/apps/{application.id}/resources', headers=auth_headers,
+ json={'cpu_limit': '1.5', 'memory_limit': '512M'})
+ assert resp.status_code == 200, resp.get_json()
+ data = resp.get_json()
+ assert data['cpu_limit'] == '1.5'
+ assert data['memory_limit'] == '512m' # normalized to lowercase
+ assert data['applied'] is False
+ assert 'note' not in data # stopped → nothing to re-apply
+
+ reloaded = Application.query.get(application.id)
+ assert reloaded.cpu_limit == '1.5'
+ assert reloaded.memory_limit == '512m'
+
+
+def test_api_put_resources_clears_with_null(client, auth_headers, app):
+ application = _make_api_app(cpu_limit='2', memory_limit='1g')
+ resp = client.put(f'/api/v1/apps/{application.id}/resources', headers=auth_headers,
+ json={'cpu_limit': None, 'memory_limit': ''})
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data['cpu_limit'] is None
+ assert data['memory_limit'] is None
+
+
+ {'cpu_limit': '-1'},
+ {'cpu_limit': 'lots'},
+ {'memory_limit': '512'},
+ {'memory_limit': 'huge'},
+])
+def test_api_put_resources_rejects_invalid(client, auth_headers, app, body):
+ application = _make_api_app()
+ resp = client.put(f'/api/v1/apps/{application.id}/resources', headers=auth_headers,
+ json=body)
+ assert resp.status_code == 400
+ assert 'error' in resp.get_json()
+
+
+def test_api_put_resources_reapplies_running_local_compose(client, auth_headers, app, monkeypatch):
+ application = _make_api_app(status='running')
+ calls = {}
+
+ def fake_compose_up(project_path, detach=True, build=False, compose_file=None):
+ calls['path'] = project_path
+ return {'success': True, 'output': ''}
+
+ monkeypatch.setattr(DockerService, 'compose_up', staticmethod(fake_compose_up))
+
+ resp = client.put(f'/api/v1/apps/{application.id}/resources', headers=auth_headers,
+ json={'cpu_limit': '1', 'memory_limit': '256m'})
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data['applied'] is True
+ assert calls['path'] == application.root_path
+
+
+def test_api_put_resources_running_reapply_failure_notes_restart(client, auth_headers, app, monkeypatch):
+ application = _make_api_app(status='running')
+ monkeypatch.setattr(DockerService, 'compose_up',
+ staticmethod(lambda *a, **k: {'success': False, 'error': 'boom'}))
+
+ resp = client.put(f'/api/v1/apps/{application.id}/resources', headers=auth_headers,
+ json={'memory_limit': '256m'})
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data['applied'] is False
+ assert data['note'] == 'restart required'
+ # The limit is still saved even though the live re-apply failed.
+ assert Application.query.get(application.id).memory_limit == '256m'
+
+
+def test_api_get_resources_404_for_missing_app(client, auth_headers, app):
+ resp = client.get('/api/v1/apps/999999/resources', headers=auth_headers)
+ assert resp.status_code == 404
diff --git a/frontend/src/components/apps/ResourceLimitsPanel.jsx b/frontend/src/components/apps/ResourceLimitsPanel.jsx
new file mode 100644
index 00000000..68edb548
--- /dev/null
+++ b/frontend/src/components/apps/ResourceLimitsPanel.jsx
@@ -0,0 +1,191 @@
+import { useState, useEffect, useCallback } from 'react';
+import { Gauge } from 'lucide-react';
+import api from '../../services/api';
+import { useToast } from '../../contexts/ToastContext';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+
+// Docker memory limit: number + one-letter unit (b/k/m/g), e.g. "512m", "2g".
+const MEMORY_LIMIT_RE = /^\d+(\.\d+)?(b|k|m|g)$/i;
+
+function validateCpu(value) {
+ const text = String(value ?? '').trim();
+ if (!text) return null; // empty = unlimited
+ const cores = Number(text);
+ if (!Number.isFinite(cores) || cores <= 0) {
+ return 'CPU limit must be a positive number of cores, e.g. 1.5';
+ }
+ return null;
+}
+
+function validateMemory(value) {
+ const text = String(value ?? '').trim();
+ if (!text) return null; // empty = unlimited
+ if (!MEMORY_LIMIT_RE.test(text)) {
+ return 'Memory limit must be a number with a unit, e.g. 512m or 2g';
+ }
+ return null;
+}
+
+// Clamp a bar width to [0, 100].
+function barWidth(percent) {
+ if (percent == null || !Number.isFinite(percent)) return 0;
+ return Math.max(0, Math.min(100, percent));
+}
+
+// Resource limits panel (task #23) — surface Docker CPU/memory caps as
+// first-class app fields with live usage next to them, instead of asking
+// people to hand-edit the compose file.
+const ResourceLimitsPanel = ({ app, onChanged }) => {
+ const toast = useToast();
+ const [cpuLimit, setCpuLimit] = useState('');
+ const [memoryLimit, setMemoryLimit] = useState('');
+ const [usage, setUsage] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [restartRequired, setRestartRequired] = useState(false);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const data = await api.getAppResources(app.id);
+ setCpuLimit(data.cpu_limit ?? '');
+ setMemoryLimit(data.memory_limit ?? '');
+ setUsage(data.usage ?? null);
+ } catch (err) {
+ console.error('Failed to load resource limits:', err);
+ } finally {
+ setLoading(false);
+ }
+ }, [app.id]);
+
+ useEffect(() => { load(); }, [load]);
+
+ const cpuError = validateCpu(cpuLimit);
+ const memoryError = validateMemory(memoryLimit);
+
+ async function handleSave() {
+ if (cpuError || memoryError) return;
+ setSaving(true);
+ try {
+ const data = await api.updateAppResources(app.id, {
+ cpu_limit: String(cpuLimit).trim() || null,
+ memory_limit: String(memoryLimit).trim() || null,
+ });
+ setRestartRequired(!data.applied && data.note === 'restart required');
+ toast.success(data.applied
+ ? 'Resource limits saved and applied.'
+ : 'Resource limits saved.');
+ onChanged?.();
+ } catch (err) {
+ toast.error(err.message || 'Failed to save resource limits');
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ // Live-usage bars. CPUPerc is % of one core, so scale it against the
+ // configured core cap when one is set; MemPerc is already % of the
+ // container's own limit.
+ const cpuCores = Number(String(cpuLimit).trim());
+ const cpuPercentOfLimit = usage?.cpu_percent != null && Number.isFinite(cpuCores) && cpuCores > 0
+ ? usage.cpu_percent / cpuCores
+ : usage?.cpu_percent;
+
+ return (
+ <div className="app-panel">
+ <div className="app-panel-header">
+ <Gauge />
+ <span>Resource Limits</span>
+ </div>
+ <div className="app-panel-body">
+ <p className="app-panel-hint">
+ Cap how much CPU and memory this service&apos;s container may use. Leave a
+ field empty for no limit. Limits are written into the generated compose
+ configuration and enforced by Docker.
+ </p>
+
+ {usage ? (
+ <>
+ <div className="resource-bar-container">
+ <div className="resource-bar-header">
+ <span className="resource-bar-label">CPU</span>
+ <span className="resource-bar-value">
+ {usage.cpu_percent != null ? `${usage.cpu_percent.toFixed(1)}%` : '—'}
+ {String(cpuLimit).trim() ? ` of ${String(cpuLimit).trim()} core(s)` : ''}
+ </span>
+ </div>
+ <div className="resource-bar-track">
+ <span
+ className="resource-bar-fill cpu"
+ style={{ width: `${barWidth(cpuPercentOfLimit)}%` }}
+ />
+ </div>
+ </div>
+ <div className="resource-bar-container">
+ <div className="resource-bar-header">
+ <span className="resource-bar-label">Memory</span>
+ <span className="resource-bar-value">
+ {usage.memory_usage || '—'}
+ {usage.memory_limit ? ` / ${usage.memory_limit}` : ''}
+ </span>
+ </div>
+ <div className="resource-bar-track">
+ <span
+ className="resource-bar-fill ram"
+ style={{ width: `${barWidth(usage.memory_percent)}%` }}
+ />
+ </div>
+ </div>
+ </>
+ ) : (
+ <p className="resource-hint">
+ {loading ? 'Loading live usage…' : 'Live usage is unavailable (service stopped or Docker stats not reachable).'}
+ </p>
+ )}
+
+ <div className="container-ops__grid">
+ <div className="container-ops__input">
+ <Label htmlFor={`res-cpu-${app.id}`}>CPU limit (cores)</Label>
+ <Input
+ id={`res-cpu-${app.id}`}
+ type="text"
+ value={cpuLimit}
+ onChange={(e) => setCpuLimit(e.target.value)}
+ placeholder="e.g. 1.5"
+ disabled={loading || saving}
+ />
+ {cpuError && <span className="error-text">{cpuError}</span>}
+ </div>
+ <div className="container-ops__input">
+ <Label htmlFor={`res-mem-${app.id}`}>Memory limit</Label>
+ <Input
+ id={`res-mem-${app.id}`}
+ type="text"
+ value={memoryLimit}
+ onChange={(e) => setMemoryLimit(e.target.value)}
+ placeholder="e.g. 512m"
+ disabled={loading || saving}
+ />
+ {memoryError && <span className="error-text">{memoryError}</span>}
+ </div>
+ </div>
+
+ {restartRequired && (
+ <p className="app-panel-hint">
+ Limits saved — restart or redeploy the service for them to take effect.
+ </p>
+ )}
+
+ <div className="app-detail-actions container-ops__actions">
+ <Button size="sm" onClick={handleSave} disabled={saving || loading || !!cpuError || !!memoryError}>
+ {saving ? 'Saving…' : 'Save limits'}
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default ResourceLimitsPanel;
diff --git a/frontend/src/components/service-detail/SettingsTab.jsx b/frontend/src/components/service-detail/SettingsTab.jsx
index 7555da13..474cea6d 100644
--- a/frontend/src/components/service-detail/SettingsTab.jsx
+++ b/frontend/src/components/service-detail/SettingsTab.jsx
@@ -12,6 +12,7 @@ import {
Hammer,
Archive,
HardDrive,
+ Gauge,
CircleCheck,
CircleX,
Sparkles,
@@ -23,6 +24,7 @@ import RepoConnectForm from '../git/RepoConnectForm';
import ProtectionPanel from '../backups/ProtectionPanel';
import ContainerOpsPanel from '../apps/ContainerOpsPanel';
import VolumesPanel from '../apps/VolumesPanel';
+import ResourceLimitsPanel from '../apps/ResourceLimitsPanel';
import AppWafPanel from '../apps/AppWafPanel';
import BuildTab from '../appdetail/BuildTab';
import DeployTab from '../appdetail/DeployTab';
@@ -53,6 +55,7 @@ function buildSettingsGroups(app) {
{ id: 'environment', label: 'Environment Type', icon: SlidersHorizontal },
{ id: 'domain', label: 'Domain & SSL', icon: Shield },
...(isDocker ? [{ id: 'ops', label: 'Container Ops', icon: Boxes }] : []),
+ ...(isDocker ? [{ id: 'resources', label: 'Resource Limits', icon: Gauge }] : []),
],
},
{
@@ -296,6 +299,15 @@ const SettingsTab = ({ app, deployConfig, domains, primaryDomain, onUpdate }) =>
</div>
)}
+ {/* Resource Limits (Docker only) — first-class CPU/memory caps
+ with live usage, instead of compose-file-only limits. */}
+ {section === 'resources' && (
+ <div className="svc-settings__section">
+ <h3 className="svc-settings__section-title">Resource Limits</h3>
+ <ResourceLimitsPanel app={app} onChanged={onUpdate} />
+ </div>
+ )}
+
{/* Storage (Docker only) — first-class managed volumes that
survive redeploys, replacing fragile relative bind mounts. */}
{section === 'storage' && (
diff --git a/frontend/src/services/api/apps.js b/frontend/src/services/api/apps.js
index 31958c0b..de046b4b 100644
--- a/frontend/src/services/api/apps.js
+++ b/frontend/src/services/api/apps.js
@@ -118,6 +118,15 @@ export async function convertAppBindMount(id, data) {
return this.request(`/apps/${id}/volumes/convert`, { method: 'POST', body: data });
}
+// Per-app resource limits (Docker CPU/memory caps) + best-effort live usage.
+export async function getAppResources(id) {
+ return this.request(`/apps/${id}/resources`);
+}
+
+export async function updateAppResources(id, data) {
+ return this.request(`/apps/${id}/resources`, { method: 'PUT', body: data });
+}
+
export async function startApp(id) {
return this.request(`/apps/${id}/start`, { method: 'POST' });
}