Download the PHP package artemyurov/laravel-autossh-tunnel without Composer
On this page you can find all versions of the php package artemyurov/laravel-autossh-tunnel. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download artemyurov/laravel-autossh-tunnel
More information about artemyurov/laravel-autossh-tunnel
Files in artemyurov/laravel-autossh-tunnel
Package laravel-autossh-tunnel
Short Description Modern SSH Tunnel Manager for Laravel with autossh support and automatic lifecycle management
License MIT
Informations about the package laravel-autossh-tunnel
Laravel AutoSSH Tunnel
Modern SSH Tunnel Manager for Laravel with autossh support and automatic lifecycle management.
Features
- 🚀 Automatic tunnel lifecycle management via callback pattern
- 🔄 AutoSSH support for automatic reconnection
- 🛡️ Comprehensive error handling with detailed messages
- 🔌 Port availability checking
- 🗄️ Laravel Database connections integration
- ⚙️ Flexible configuration (env, config files or direct parameters)
- ✅ Configuration validation
- 📝 Detailed logging
- 🎯 Multiple simultaneous tunnels support
Installation
Publish Configuration
After publishing, copy the tunnel environment variables to your .env:
Configuration
Environment Variables
The configuration uses a clear logical order:
- SSH Connection - How to connect to the SSH server
- Remote/Local - What to forward and where
- SSH Options - Connection behavior settings
Configuration File
After publishing the config, edit config/tunnel.php:
Multiple Connections Example
For multiple tunnel connections, use unique prefixes for each connection:
Tunnel Types
The package supports two types of SSH tunnels:
Forward Tunnel (-L) - Access Remote Services
Forward tunnels allow you to access remote services from your local machine.
SSH Command:
Use Cases:
- Access production/staging databases for debugging
- Connect to internal APIs not exposed to the internet
- Access remote services (Redis, Elasticsearch, etc.)
- Secure connection to remote development environments
Example:
Reverse Tunnel (-R) - Expose Local Services
Reverse tunnels expose your local application to a remote server, making it accessible from the internet.
SSH Command:
Important: remote_host is the bind address on the remote server:
localhost- tunnel accessible only locally on remote server (127.0.0.1:8080)0.0.0.0- tunnel publicly accessible (your-server.com:8080 from internet)
Use Cases:
- Test webhooks locally (Stripe, PayPal, GitHub, Telegram)
- Demo local application to clients without deployment
- Temporary public access to development environment
- Receive callbacks from external services
Example:
Usage
Callback Pattern (Recommended)
Automatic tunnel closure after execution:
With Laravel Database Integration
Manual Management
Multiple Tunnels Simultaneously
Using in Artisan Commands
Long-Running Tunnels
For persistent tunnels that stay active (similar to ngrok), use the Artisan commands:
Start with Live Monitoring
Start a tunnel with real-time status updates (like ngrok):
This will show a live dashboard with tunnel information:
Press Ctrl+C to gracefully stop the tunnel.
Start in Background (Daemon Mode)
Run tunnel in background without monitoring (detached daemon mode):
Check Tunnel Status
View status of running tunnels:
Stop Tunnel
Stop a running tunnel:
Run as System Service
For production environments, you can run the tunnel as a persistent systemd service.
📖 See detailed guide: SYSTEMD.md
Quick example:
Related Resources
- Running as systemd Service - Complete guide for production deployments
- Self-hosted ngrok alternative - Building your own tunnel infrastructure
AutoSSH
The package automatically detects autossh availability and uses it instead of regular ssh to provide automatic reconnection on connection loss.
Installing autossh
macOS:
Ubuntu/Debian:
The package uses command -v autossh to detect autossh automatically. No additional configuration needed.
Disable AutoSSH
If you want to use regular SSH even when autossh is available:
Docker & DDEV
SSH tunnels work inside containers — you need access to SSH keys and autossh installed.
DDEV (Docker Desktop)
DDEV runs on Docker Desktop, which provides built-in
SSH agent forwarding
through the socket /run/host-services/ssh-auth.sock.
-
Add
autosshtoconfig.yaml: -
Create
.ddev/docker-compose.ssh-auth-socket.yamlfor SSH agent forwarding: - Restart and verify:
Docker Compose (Server / Docker Engine)
On servers there is no Docker Desktop, so SSH agent forwarding via
/run/host-services/ssh-auth.sock is not available. Instead, mount the host's
~/.ssh directory directly into the container (read-only).
-
Add
openssh-client autosshto your Dockerfile: - Create
docker-compose.ssh-keys.yaml:
Note: Adjust the target path (
/root/.ssh) to match the user running the application inside the container (e.g./home/www-data/.sshor/var/www/.ssh).
-
Include it via
COMPOSE_FILEin.env: - Rebuild and verify:
Error Handling
Important Notes
MySQL/MariaDB: localhost vs 127.0.0.1
Critical: In MySQL and MariaDB, localhost has a special hardcoded meaning - it always represents a Unix socket connection, not a TCP/IP connection. This behavior cannot be changed.
The Difference
localhost→ Unix socket connection (/var/run/mysqld/mysqld.sock)127.0.0.1→ TCP/IP connection over loopback interface
When using SSH tunnels with MySQL/MariaDB:
Configuration Example
Environment Variables:
Tunnel Configuration:
Database User Permissions
MySQL/MariaDB treat user@localhost and [email protected] as different users:
Important: When using SSH tunnels to access remote MySQL/MariaDB:
- Create database user with
@127.0.0.1host (not@localhost) - Set
remote_hostto127.0.0.1in tunnel config - Use
'host' => '127.0.0.1'in database connection config
Why This Matters
This issue commonly occurs when:
- Remote server's
localhostresolves to IPv6 (::1) - Database user only has
@localhost(Unix socket) permissions - Database rejects connections: "Host '::1' is not allowed to connect"
Solution: Always use 127.0.0.1 for both remote_host in tunnel config and database connection host when working with MySQL/MariaDB over SSH tunnels.
Advanced Features
Tunnel Reuse
The package can automatically detect and reuse existing SSH tunnels instead of creating new ones. This is useful for:
- Avoiding "port already in use" errors
- Sharing tunnels between multiple processes
- Faster command execution (no tunnel startup time)
Smart Tunnel Discovery
The package uses two methods to find existing tunnels:
- PID file - Fastest method, stores tunnel PID in temp directory
- Port scan - Uses
lsof/netstatto find processes by port
Reuse Command
Find and reuse existing tunnel from command line:
Retry Logic
Execute database operations with automatic retry on connection errors:
If the operation fails due to connection error, the tunnel will automatically reconnect and retry the operation.
Configuration
Configure retry behavior in config/tunnel.php:
Or use environment variables:
Database Validation
Verify that database is actually accessible through tunnel (not just port checking):
Signal Handling
Tunnels can automatically handle system signals for graceful shutdown:
Requires pcntl extension. Configure in config/tunnel.php:
Keep-Alive Tunnels
Create tunnels that persist after script ends:
To stop keep-alive tunnel, use the stop command:
Diagnostic Tools
Diagnose Command
Comprehensive tunnel health check:
The diagnostic tool checks:
- ✓ Configuration existence
- ✓ Process running (PID file + port scan)
- ✓ Process is SSH
- ✓ Port accessibility
- ✓ Database accessibility (optional)
ManagesTunnel Trait for Commands
Convenient trait for managing tunnels in Laravel commands:
ManagesTunnel Methods
setupTunnel($connection, $dbConfig, $keepAlive, $validateDb)- Initialize tunnelensureTunnelConnected($maxAttempts)- Check and reconnect if neededwithTunnelRetry($operation, $maxAttempts)- Execute with retryvalidateTunnelDatabase($connection, $timeout, $wait)- Validate databasevalidateTunnel($connection)- Full validationcloseTunnel()- Graceful shutdownisTunnelRunning()- Check statusgetTunnel()/getTunnelConnection()- Get instances
API Reference
Artisan Commands
tunnel:start {connection?} {--detach}- Start tunnel with live monitoring (or in background with --detach)tunnel:stop {connection?} {--all}- Stop tunnel (or all tunnels with --all)tunnel:status {connection?} {--all}- Show tunnel status (or all tunnels with --all)tunnel:reuse {connection?} {--db-connection=} {--db-driver=} {--db-database=} {--db-username=} {--db-password=}- Find and reuse existing tunneltunnel:diagnose {connection?} {--db-connection=} {--verbose}- Diagnose tunnel health
Tunnel
Static Methods
Tunnel::connection(?string $name = null): Tunnel- Create from config/tunnel.phpTunnel::fromConfig(TunnelConfig $config): Tunnel- Create from config object
Instance Methods
withDatabaseConnection(string $name, array $config): self- Register Laravel DB connectionstart(): TunnelConnection- Start tunnelreuseOrCreate(): TunnelConnection- Smart tunnel reuse or creationfindExistingByPort(): ?int- Find existing tunnel by port using lsofensureConnected(int $maxAttempts = 3): bool- Ensure tunnel is active, reconnect if neededexecute(callable $callback): mixed- Execute callback with automatic tunnel managementgetConfig(): TunnelConfig- Get configurationgetConnection(): ?TunnelConnection- Get active connection
TunnelConnection
isRunning(): bool- Check if tunnel is runninggetPid(): ?int- Get process PIDstop(): void- Stop tunnelverifyConnection(): bool- Verify tunnel availabilityensureConnected(int $maxAttempts = 3): bool- Reconnect if tunnel is downwithKeepAlive(bool $keepAlive = true): self- Set keep-alive flagsetupSignalHandlers(): self- Setup SIGINT/SIGTERM handlersvalidateDatabase(string $connectionName, int $timeout = 5): bool- Validate database accessibilitywaitForDatabase(string $connectionName, int $maxAttempts = 5, int $delaySeconds = 2): bool- Wait for database with retriesexecuteWithRetry(callable $operation, ?int $maxAttempts = null): mixed- Execute with automatic retryvalidate(?string $connectionName = null): array- Full validation (process + port + database)
TunnelManager
saveTunnel(string $name, TunnelConnection $connection): void- Save tunnel info to storagegetTunnelInfo(string $name): ?array- Get tunnel informationstopTunnel(string $name): bool- Stop tunnel by namegetAllTunnels(): array- Get all running tunnelsgetUptime(array $info): int- Get tunnel uptime in secondsformatUptime(int $seconds): string- Format uptime as human-readable string
Logging
The package uses standard Laravel Log facade. For detailed logging:
Or in config/tunnel.php:
Requirements
- PHP ^8.2
- Laravel ^10.0|^11.0|^12.0|^13.0
- SSH client installed on the system
- AutoSSH (optional, for auto-reconnection)
License
MIT License
Author
Artem Yurov ([email protected])
All versions of laravel-autossh-tunnel with dependencies
illuminate/support Version ^10.0|^11.0|^12.0|^13.0
illuminate/config Version ^10.0|^11.0|^12.0|^13.0
illuminate/log Version ^10.0|^11.0|^12.0|^13.0
symfony/process Version ^6.0|^7.0|^8.0