@@ -416,21 +416,56 @@ def restart_services(
416416 logger .info (f"Found wsgi.py in { wsgi_path } , project: { project_name } " )
417417 logger .info (f"Running Gunicorn for { project_name } in background..." )
418418
419- # Command to launch Gunicorn in background, disowned
420- cmd = (
421- f"bash -c 'cd { project_dir } && "
422- f"export PYTHONPATH={ current_path } && "
423- f"{ gunicorn_bin } --workers=3 "
424- f"--bind=unix:{ socket_path } "
425- f"{ project_name } .wsgi:application "
426- f"--access-logfile { access_log } "
427- f"--error-logfile { error_log } "
428- f"--log-level=info &' disown"
419+ # Kill previous Gunicorn processes for this site
420+ kill_cmd = (
421+ f"ps -eo pid,cmd | grep gunicorn | grep '{ socket_path } ' "
422+ f"| awk '{{print $1}}' | xargs -r kill"
429423 )
430-
431- # Execute the command
424+ logger .info (f"Stopping previous Gunicorn processes for { site } ..." )
425+ c .run (kill_cmd , warn = True )
426+
427+ # Generate a unique name for the script
428+ script_name = f"/tmp/start_gunicorn_{ uuid .uuid4 ().hex } .sh"
429+
430+ # Content of the script to start Gunicorn
431+ script_content = f"""#!/bin/bash
432+ cd { project_dir }
433+ export PYTHONPATH={ current_path }
434+ { gunicorn_bin } --workers=3 \\
435+ --bind=unix:{ socket_path } \\
436+ { project_name } .wsgi:application \\
437+ --access-logfile { access_log } \\
438+ --error-logfile { error_log } \\
439+ --log-level=info
440+ """
441+
442+ # Create the script on the remote server
443+ c .run (f"cat > { script_name } << 'EOL'\n { script_content } \n EOL" , hide = True )
444+ c .run (f"chmod +x { script_name } " , hide = True )
445+
446+ # Execute the script with nohup and in background
447+ cmd = f"nohup { script_name } >/dev/null 2>&1 </dev/null & sleep 1"
432448 c .run (cmd , pty = False )
433449
450+ # Delete the script after using it (optional, executed in background)
451+ c .run (f"(sleep 5 && rm -f { script_name } &)" , pty = False )
452+
453+ logger .info (f"Gunicorn process for { site } has been launched" )
454+
455+ # Optionally, verify if the process is running
456+ check_cmd = (
457+ f"ps -eo pid,cmd | grep gunicorn | "
458+ f"grep '{ socket_path } ' | grep -v grep"
459+ )
460+ result = c .run (check_cmd , warn = True , hide = True )
461+ if result and not result .failed and result .stdout .strip ():
462+ logger .info (f"Verified Gunicorn is running for { site } " )
463+ else :
464+ logger .warning (
465+ f"Could not verify if Gunicorn started for { site } . "
466+ "Check logs manually."
467+ )
468+
434469def set_writable_dirs (
435470 c : Connection | DockerRunner | Context ,
436471 config : dict
0 commit comments