Deploy dbbasic-web apps to Ubuntu servers over SSH: nginx, Let's Encrypt and systemd, no Docker or Ansible.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-deploy.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-deploy.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-deploy.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add PyPI metadata (keywords, classifiers) 00ed320 1 year, 1 month ago History
deploy.py · 3.8 KB · 112 lines
1"""Deployment commands for dbbasic-web apps."""
2
3import os
4import paramiko
5from paramiko import SFTPClient
6
7
8def deploy_app(host, domain, app_name="app", port=3000, user="root", key_path=None, local_path="."):
9 """
10 Deploy a dbbasic-web app to Ubuntu server.
11
12 Steps:
13 1. Copy code to server
14 2. Install dependencies
15 3. Restart service
16 4. Check health
17 """
18 print(f"Deploying to {host}...")
19
20 ssh = paramiko.SSHClient()
21 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
22
23 # Connect
24 connect_kwargs = {"hostname": host, "username": user}
25 if key_path:
26 connect_kwargs["key_filename"] = key_path
27
28 ssh.connect(**connect_kwargs)
29
30 def run(command, description=None, check=True):
31 """Run command and print output."""
32 if description:
33 print(f" {description}...")
34 stdin, stdout, stderr = ssh.exec_command(command)
35 exit_status = stdout.channel.recv_exit_status()
36 output = stdout.read().decode()
37 error = stderr.read().decode()
38
39 if check and exit_status != 0:
40 print(f" Error: {error}")
41 raise Exception(f"Command failed: {command}")
42
43 if output:
44 for line in output.strip().split('\n'):
45 print(f" {line}")
46 return output, exit_status
47
48 # Create temp directory for upload
49 temp_dir = f"/tmp/{app_name}-deploy"
50 run(f"rm -rf {temp_dir} && mkdir -p {temp_dir}", "Preparing temp directory")
51
52 # Upload files via SFTP
53 print(" Uploading files...")
54 sftp = ssh.open_sftp()
55
56 def upload_directory(local_dir, remote_dir):
57 """Recursively upload directory."""
58 for item in os.listdir(local_dir):
59 local_item = os.path.join(local_dir, item)
60 remote_item = f"{remote_dir}/{item}"
61
62 # Skip common directories to ignore
63 if item in ['__pycache__', '.git', 'venv', 'node_modules', '.DS_Store', 'var']:
64 continue
65
66 if os.path.isfile(local_item):
67 sftp.put(local_item, remote_item)
68 print(f" Uploaded {item}")
69 elif os.path.isdir(local_item):
70 try:
71 sftp.mkdir(remote_item)
72 except IOError:
73 pass # Directory might already exist
74 upload_directory(local_item, remote_item)
75
76 upload_directory(local_path, temp_dir)
77 sftp.close()
78
79 # Move to app directory
80 app_dir = f"/var/www/{app_name}"
81 run(f"sudo -u {app_name} rm -rf {app_dir}/*", "Clearing app directory")
82 run(f"sudo -u {app_name} cp -r {temp_dir}/* {app_dir}/", "Moving files to app directory")
83 run(f"rm -rf {temp_dir}", "Cleaning up")
84
85 # Create venv if it doesn't exist
86 output, status = run(f"sudo -u {app_name} test -d {app_dir}/venv", check=False)
87 if status != 0:
88 run(f"sudo -u {app_name} python3.12 -m venv {app_dir}/venv", "Creating virtual environment")
89
90 # Install dependencies
91 run(f"sudo -u {app_name} {app_dir}/venv/bin/pip install --upgrade pip", "Upgrading pip")
92 run(f"sudo -u {app_name} {app_dir}/venv/bin/pip install -r {app_dir}/requirements.txt",
93 "Installing dependencies")
94
95 # Restart service
96 run(f"systemctl restart {app_name}", "Restarting service")
97 run(f"systemctl enable {app_name}", "Enabling service")
98
99 # Check status
100 output, status = run(f"systemctl is-active {app_name}", "Checking service status", check=False)
101 if status == 0:
102 print(f"\n✓ Deployment successful!")
103 print(f"\nYour app is running at:")
104 print(f" http://{domain}")
105 print(f"\nTo check logs:")
106 print(f" ssh {user}@{host} 'journalctl -u {app_name} -f'")
107 else:
108 print(f"\n✗ Service failed to start")
109 print(f"\nCheck logs:")
110 print(f" ssh {user}@{host} 'journalctl -u {app_name} -n 50'")
111
112 ssh.close()