How to Set Up Laravel 13 with LaravelS, Nginx, WebSocket, and Async Tasks
Laravel is a popular PHP framework for building web applications and APIs. When an application needs a high-performance HTTP server, WebSocket communication, or asynchronous task processing, LaravelS provides an alternative runtime powered by Swoole.
This guide explains how to initialize a Laravel 13 project, install LaravelS, configure Nginx as a reverse proxy, and enable WebSocket and asynchronous task processing.
1. Environment Requirements
The examples in this article use the following environment:
| Component | Version |
|---|---|
| PHP | 8.5.12 |
| Laravel | 13.x |
| LaravelS | 3.8.x |
| Swoole | 5.0+ |
| Nginx | Installed |
| Composer | Latest stable |
Laravel 13 requires PHP 8.3 or higher and supports PHP 8.5.
LaravelS 3.8.x supports Laravel 10 and later, PHP 8.2 and later, and Swoole 5.0 or later.
Make sure the required PHP extensions are installed, including intl, curl, json, and pcntl.
Check your PHP environment:
php -v
php -m
composer --version
Check whether Swoole is available:
php --ri swoole
If the extension is not installed, install a Swoole version compatible with your PHP 8.5 environment before continuing.
2. Create a Laravel 13 Project
Create a new Laravel project using Composer:
composer create-project laravel/laravel my-project
Enter the project directory:
cd my-project
If you are initializing an existing project from a Git repository, make sure the environment file exists:
cp .env.example .env
Generate the application encryption key:
php artisan key:generate
At this point, the basic Laravel application is ready.
3. Install and Initialize LaravelS
LaravelS is an adapter between Laravel and Swoole. It provides an HTTP server, WebSocket support, asynchronous task processing, and other server-side capabilities.
Install LaravelS through Composer:
composer require "hhxsv5/laravel-s:~3.8.0"
Laravel 5.5 and later supports automatic package discovery, so manually registering the service provider is generally unnecessary.
Publish the LaravelS configuration and executable scripts:
php artisan laravels publish
This command generates the following files:
config/laravels.php- LaravelS configuration.bin/laravels- Server management script.bin/fswatchandbin/inotify- File monitoring utilities.
The main configuration file is:
config/laravels.php
You can customize the listening address, port, worker processes, WebSocket settings, and task workers in this file.
4. Configure the LaravelS HTTP Server
By default, LaravelS listens on port 5200.
Make sure the server listens on the loopback interface if Nginx is running on the same machine:
'listen_ip' => '127.0.0.1',
'listen_port' => 5200,
The exact configuration structure may vary slightly depending on the published LaravelS version.
You can now start LaravelS:
php bin/laravels start
Start it in daemon mode:
php bin/laravels start -d
Common management commands include:
# Start the server
php bin/laravels start
# Stop the server
php bin/laravels stop
# Restart the server
php bin/laravels restart
# Gracefully reload worker processes
php bin/laravels reload
# Display version information
php bin/laravels info
Use reload after modifying application code. If you modify config/laravels.php, use restart to apply the configuration changes.
5. Configure Nginx as a Reverse Proxy
In a production environment, Nginx can handle incoming HTTP requests and forward dynamic requests to LaravelS.
Nginx can also serve static files directly, reducing unnecessary requests to the application server.
For example, create an Nginx virtual host configuration:
upstream laravels {
server 127.0.0.1:5200;
keepalive 16;
}
server {
listen 80;
server_name example.com;
root /var/www/my-project/public;
index index.html;
location / {
try_files $uri @laravels;
}
location @laravels {
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://laravels;
}
}
Replace example.com and /var/www/my-project/public with your actual domain and project path.
The try_files directive allows Nginx to serve existing static files directly. Requests that do not match an existing file are forwarded to LaravelS.
Test the Nginx configuration:
sudo nginx -t
Reload Nginx:
sudo systemctl reload nginx
6. Enable WebSocket Support
LaravelS includes a built-in WebSocket server powered by Swoole.
To enable it, create a WebSocket handler class.
For example, create:
app/Services/WebSocketService.php
Implement the WebSocketHandlerInterface:
<?php
namespace App\Services;
use Hhxsv5\LaravelS\Swoole\WebSocketHandlerInterface;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;
class WebSocketService implements WebSocketHandlerInterface
{
public function __construct()
{
}
public function onOpen(Server $server, Request $request)
{
$server->push(
$request->fd,
'WebSocket connection established'
);
}
public function onMessage(Server $server, Frame $frame)
{
$server->push(
$frame->fd,
'Received: ' . $frame->data
);
}
public function onClose(Server $server, $fd, $reactorId)
{
// Handle connection closure.
}
}
Next, enable WebSocket support in config/laravels.php:
'websocket' => [
'enable' => true,
'handler' => \App\Services\WebSocketService::class,
],
Also configure the Swoole dispatch mode:
'swoole' => [
// Other settings...
'dispatch_mode' => 2,
],
The WebSocket server shares the main LaravelS listening address and port.
In this example, the WebSocket endpoint will be:
ws://127.0.0.1:5200/ws
Make sure the corresponding /ws route is registered in Laravel so that the WebSocket handshake request can pass through Laravel’s routing and middleware.
7. Configure Nginx for WebSocket Connections
WebSocket connections require HTTP protocol upgrades.
Nginx must forward the Upgrade and Connection headers to LaravelS.
Add the following configuration inside the Nginx http context:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
Then add a WebSocket location to your server configuration:
location = /ws {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
proxy_pass http://laravels;
}
The /ws path is only an example. Change it if your application uses a different WebSocket endpoint.
The longer proxy timeout helps prevent Nginx from closing idle WebSocket connections prematurely. You should also configure Swoole heartbeat settings to detect inactive connections.
For example:
'swoole' => [
// Other settings...
'heartbeat_idle_time' => 600,
'heartbeat_check_interval' => 60,
],
After modifying the configuration, restart LaravelS and reload Nginx.
8. Enable Asynchronous Task Processing
LaravelS supports asynchronous task processing through Swoole’s task worker mechanism.
This is useful for operations that do not need to block the HTTP response, such as:
- Sending emails.
- Processing uploaded files.
- Generating reports.
- Performing time-consuming background operations.
- Running additional business logic after an API request.
First, configure the number of task worker processes in config/laravels.php:
'swoole' => [
// Other settings...
'task_worker_num' => 4,
],
The number of task workers should be adjusted according to your workload and server resources.
Create a Task Class
Create a task class, for example:
app/Tasks/ExampleTask.php
Implement the LaravelS Task base class:
<?php
namespace App\Tasks;
use Hhxsv5\LaravelS\Swoole\Task\Task;
class ExampleTask extends Task
{
protected $data;
public function __construct($data)
{
$this->data = $data;
}
public function handle()
{
// Execute background operations here.
\Log::info('Background task started', [
'data' => $this->data,
]);
// Simulate a time-consuming operation.
sleep(2);
}
}
The handle() method runs inside a Swoole task worker process.
Dispatch an Asynchronous Task
You can dispatch the task from a controller or another application service:
use App\Tasks\ExampleTask;
use Hhxsv5\LaravelS\Swoole\Task\Task;
class ExampleController
{
public function index()
{
$success = Task::deliver(
new ExampleTask('Hello LaravelS')
);
return response()->json([
'success' => $success,
]);
}
}
Task::deliver() submits the task asynchronously.
It returns a boolean indicating whether the task was successfully submitted. It does not mean that the background operation has already completed.
For important business operations, consider implementing logging, retries, failure handling, and persistent queue mechanisms where necessary.
9. Start and Verify the Complete Application
After configuring HTTP, WebSocket, and asynchronous task processing, restart LaravelS:
php bin/laravels restart
Check the Nginx configuration:
sudo nginx -t
Reload Nginx:
sudo systemctl reload nginx
You can now test the following services:
| Service | Example |
|---|---|
| HTTP | http://example.com |
| WebSocket | ws://example.com/ws |
| LaravelS | 127.0.0.1:5200 |
For WebSocket testing, you can use a browser console:
const ws = new WebSocket('ws://example.com/ws');
ws.onopen = () => {
console.log('Connected');
ws.send('Hello LaravelS');
};
ws.onmessage = (event) => {
console.log('Received:', event.data);
};
For HTTPS websites, use wss:// instead of ws://.
10. Production Deployment Considerations
Before deploying LaravelS to production, consider the following points.
Process management
Use Supervisor or another process manager to keep LaravelS running.
LaravelS recommends running under Supervisor without daemon mode. Set swoole.daemonize to false and let Supervisor manage the main process.
Memory management
Unlike traditional PHP-FPM, LaravelS keeps worker processes alive between requests. Avoid relying on request-level cleanup of global or static variables.
Be careful with static properties, singleton services, and shared application state.
WebSocket connection management
Maintain a mapping between authenticated user IDs and Swoole file descriptors if you need to push messages to specific users.
For multiple server instances, use Redis or another shared storage mechanism rather than relying only on local Swoole tables.
Task worker sizing
Adjust task_worker_num based on task processing time, throughput, and available memory.
Coroutine compatibility
Do not enable coroutine hooks indiscriminately in a Laravel application. Laravel and its dependencies may contain shared state and singleton resources that are not safe for concurrent coroutine execution.
Conclusion
LaravelS provides a convenient way to run Laravel applications on top of Swoole while adding support for HTTP services, WebSocket communication, and asynchronous task processing.
The complete setup consists of:
- Creating a Laravel 13 project.
- Installing and publishing LaravelS.
- Configuring the Swoole HTTP server.
- Setting up Nginx as a reverse proxy.
- Enabling WebSocket support.
- Configuring asynchronous task workers.
- Testing and managing the production service.
With these components working together, Laravel applications can support persistent HTTP workers, real-time communication, and background processing in a unified server environment.
