Laravel WebSockets as a Service

Recently Beyondcode came out with a web sockets package for Laravel.  For my mailroom project I decided to add push notifications when a service receives a webhook.  This a great use case for Laravel WebSockets package.  In this article we will take a look at how to install it as a service using Docker and use websockets demo application to test it.

First of all install Laravel application in “websockets” folder.  Use instructions to install WebSockets package.  The .env file for the application should look the following:

WebSockets package uses database to log some statistics data.  You have to have a working database connection. Since our app will be running in a container, you will have to use an ip address to connect to your database.  I usually have my database on a separate server.

PUSHER_APP_ID=testapp
PUSHER_APP_KEY=websocketkey
PUSHER_APP_SECRET=somethingsecret

The above credentials are taken straight from the .env file of the websockets demo application.  You may change them if you like.  Just be sure they are consistent between websockets server and the demo application.

Now outside the “websockets” folder let’s create Dockerfile.  

We are using Ubuntu 16.04 and installing php packages.  Although WebSockets have features such as Debugging Dashboard we will be running the service as a bare minimum.  We are not installing php-fpm or nginx into the container.  To keep the process running we are using Supervisor.  Therefore we need to create supervisord.conf file outside “websockets” directory (in the same directory as Dockerfile):

Now we are ready to create an image:

docker build -t localhost:5000/websockets.com/app:v1

You can notice I am using a local docker repository.  You may tag your image the way it seems appropriate to you.  Now we can start up a container for the service.  Normally I push an image to my repository, pull it on a webserver and run a container there.

docker run -d -p 6001:6001 \
–restart=unless-stopped \
–name=websockets \
localhost:5000/websockets.com/app:v1

All we have to do is to run migrations: sudo docker exec websockets sh -c “cd /var/www/html && php artisan migrate –force”  WebSockets service should be up and listening on port 6001.  Be sure this port is open on your server.  

Let’s test it.  Install the laravel websockets demo application as described except for do not run php artisan websockets:serve in step 6.  In resources/js/bootstrap.js file set wsHost to the ip address of your server where WebSockets are running.  Also in config/broadcasting.php set pusher’s connection (‘host’) to point to your server’s ip adderss.  Recompile javascript: npm install (if needed) / npm run production (or dev).  You are all set.

Resources used:

Laravel WebSockets Documentation

Shipping Docker Course