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.

Enhance app deletion and improve port allocation logic

Juan Denisc7eaafab6aea
diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py
index a24b0467..08e4201d 100644
--- a/backend/app/api/apps.py
+++ b/backend/app/api/apps.py
@@ -1,3 +1,4 @@
+import os
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
@@ -121,6 +122,9 @@ def update_app(app_id):
@apps_bp.route('/<int:app_id>', methods=['DELETE'])
@jwt_required()
def delete_app(app_id):
+ import shutil
+ from app.services.nginx_service import NginxService
+
current_user_id = get_jwt_identity()
user = User.query.get(current_user_id)
app = Application.query.get(app_id)
@@ -131,10 +135,46 @@ def delete_app(app_id):
if user.role != 'admin' and app.user_id != current_user_id:
return jsonify({'error': 'Access denied'}), 403
+ cleanup_results = {
+ 'docker': None,
+ 'folder': None,
+ 'nginx': None
+ }
+
+ # For Docker apps, stop and remove containers/volumes
+ if app.app_type == 'docker' and app.root_path:
+ try:
+ # Stop and remove containers, networks, and volumes
+ result = DockerService.compose_down(app.root_path, volumes=True, remove_orphans=True)
+ cleanup_results['docker'] = result
+ except Exception as e:
+ cleanup_results['docker'] = {'error': str(e)}
+
+ # Delete the app folder
+ try:
+ if app.root_path and app.root_path.startswith('/var/serverkit/apps/'):
+ if os.path.exists(app.root_path):
+ shutil.rmtree(app.root_path)
+ cleanup_results['folder'] = {'success': True}
+ except Exception as e:
+ cleanup_results['folder'] = {'error': str(e)}
+
+ # Remove nginx site config
+ try:
+ NginxService.disable_site(app.name)
+ NginxService.delete_site(app.name)
+ cleanup_results['nginx'] = {'success': True}
+ except Exception as e:
+ cleanup_results['nginx'] = {'error': str(e)}
+
+ # Delete from database
db.session.delete(app)
db.session.commit()
- return jsonify({'message': 'Application deleted successfully'}), 200
+ return jsonify({
+ 'message': 'Application deleted successfully',
+ 'cleanup': cleanup_results
+ }), 200
@apps_bp.route('/<int:app_id>/start', methods=['POST'])
diff --git a/backend/app/services/template_service.py b/backend/app/services/template_service.py
index 96d7e755..1b9e355a 100644
--- a/backend/app/services/template_service.py
+++ b/backend/app/services/template_service.py
@@ -143,18 +143,7 @@ class TemplateService:
return ''.join(secrets.choice(chars) for _ in range(length))
elif var_type == 'port':
- # Find available port starting from default
- import socket
- start_port = int(default) if default else 8000
- for port in range(start_port, start_port + 100):
- try:
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.bind(('', port))
- sock.close()
- return str(port)
- except OSError:
- continue
- return str(start_port)
+ return str(cls._find_available_port(int(default) if default else 8000))
elif var_type == 'uuid':
import uuid
@@ -166,6 +155,74 @@ class TemplateService:
return str(default)
+ @classmethod
+ def _find_available_port(cls, start_port: int = 8000, max_attempts: int = 100) -> int:
+ """Find an available port that's not in use by the system or Docker.
+
+ Checks both socket binding and Docker container port mappings.
+ """
+ import socket
+
+ # Get ports currently used by Docker containers
+ docker_ports = cls._get_docker_used_ports()
+
+ for port in range(start_port, start_port + max_attempts):
+ # Skip if Docker is using this port
+ if port in docker_ports:
+ continue
+
+ # Check if port is available on localhost (where Docker binds)
+ try:
+ # Check 127.0.0.1 specifically since Docker binds there
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.settimeout(1)
+ result = sock.connect_ex(('127.0.0.1', port))
+ sock.close()
+
+ # If connection failed, port is available
+ if result != 0:
+ # Double-check by trying to bind
+ try:
+ test_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ test_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ test_sock.bind(('127.0.0.1', port))
+ test_sock.close()
+ return port
+ except OSError:
+ continue
+ except Exception:
+ continue
+
+ # Fallback: return a high port number
+ return start_port + max_attempts
+
+ @classmethod
+ def _get_docker_used_ports(cls) -> set:
+ """Get all ports currently mapped by Docker containers."""
+ used_ports = set()
+ try:
+ result = subprocess.run(
+ ['docker', 'ps', '--format', '{{.Ports}}'],
+ capture_output=True,
+ text=True,
+ timeout=10
+ )
+ if result.returncode == 0:
+ # Parse port mappings like "0.0.0.0:8080->80/tcp, 127.0.0.1:3306->3306/tcp"
+ import re
+ for line in result.stdout.strip().split('\n'):
+ if line:
+ # Find all host ports in the format "host:port->container"
+ matches = re.findall(r'(?:[\d.]+:)?(\d+)->', line)
+ for port_str in matches:
+ try:
+ used_ports.add(int(port_str))
+ except ValueError:
+ pass
+ except Exception:
+ pass
+ return used_ports
+
@classmethod
def substitute_variables(cls, content: str, variables: Dict) -> str:
"""Substitute variables in content using ${VAR} syntax."""