You need two shell scripts in your project root to manage the connection. Each project should use a unique LOCAL_PORT (e.g., 3307, 3308) to avoid conflicts.
start-tunnel-[project].sh
This script checks if the port is in use, and if not, creates a background SSH tunnel using ssh -f -N -L.
stop-tunnel-[project].sh
This script finds the process ID (PID) listening on the specified LOCAL_PORT and kills it.
After creating them, make them executable:
chmod +x start-tunnel-*.sh stop-tunnel-*.sh
#!/bin/bash
# SSH Tunnel for [PROJECT] project
LOCAL_PORT=33XX # Use unique port (3307, 3308, 3309, etc.)
REMOTE_SERVER="your.server.com" # Your SSH server
SSH_PORT=1022 # SSH port (often 1022 or 22)
SSH_USER="your_ssh_user" # SSH username
echo "🔗 Starting SSH tunnel for [PROJECT] project..."
echo "📊 Local port: $LOCAL_PORT"
echo "🌐 Remote server: $REMOTE_SERVER:$SSH_PORT"
echo "👤 User: $SSH_USER"
# Check if port is already in use
if lsof -Pi :$LOCAL_PORT -sTCP:LISTEN -t >/dev/null ; then
echo "⚠️ Port $LOCAL_PORT already in use - tunnel may already be running"
exit 0
fi
# Create the SSH tunnel
ssh -f -N -L $LOCAL_PORT:localhost:3306 -p $SSH_PORT $SSH_USER@$REMOTE_SERVER
if [ $? -eq 0 ]; then
sleep 2
if lsof -Pi :$LOCAL_PORT -sTCP:LISTEN -t >/dev/null ; then
echo "✅ [PROJECT] SSH tunnel created successfully on port $LOCAL_PORT"
else
echo "❌ Tunnel creation failed"
exit 1
fi
else
echo "❌ Failed to create SSH tunnel"
exit 1
fi