Adding Browser Sync to Laravel and Docker with Vessel


I recently stumbled upon Vessel by Chris Fidao which is a great way to leverage Docker in your development environment. I'm a big fan of Docker and use it extensively for home lab work, but haven't fully explored it for development yet.

Getting it going with some Laravel projects I had on hand was super smooth and will probably be my new choice for development going forward. However, I was still hoping to fix an issue I've been having developing on WSL 2--getting Browser Sync to work. It's one of the biggest annoyances when working in Window's WSL 2 versus on macOS.

After some playing around with the config files Vessel generates, I've gotten Browser Sync to work with it--which also means it works in WSL 2 thanks to Docker!

First this assumes you have a relatively new Laravel project (version 6 or 7) and have set up Vessel without any major customizations.

First lets update our .env to reduce any port conflicts, changing the APP port and MYSQL port as appropriate.

# .env

Running ./vessel start should get your containers up and running with your defined ports--great! Next we're going to ensure you've Browser Sync included in your dependencies.

./vessel npm i browser-sync browser-sync-webpack-plugin --save-dev

Update your webpack.mix.js to leverage the new package. Here you can choose whether just to watch for files going through the webpack pipeline (CSS and JS) or also include any changes to your Blade templates or even user content.

// webpack.mix.js
mix.js("resources/js/app.js", "public/js")
    .sass("resources/sass/app.scss", "public/css")
        proxy: "app:80",
        open: false,

The magic line is app:80--this should be equal to the container Vessel created for you. It should be called app. To confirm run ./vessel ps and look for one that has app in the title. If you run into issues, it may also be called yourappname_app_1.

The port by default is 80 but change this if you've changed your docker_compose.yml file to something else. This should be the internal container port, not the port you used to view your site (in this case 8080 as defined earlier).

Finally, we're going to tell Docker to expose the Browser Sync ports, as well as a default command to ensure the container doesn't immediately exit and opens the ports for you.

# docker-compose.yml
    command: npm run watch
        - "3000:3000"
        - "3001:3001"

Finally, let's stop and start our containers, and if all went well we should see our Browser Sync connected app at localhost:3000!

./vessel stop && ./vessel start

If you don't initially see your app, you can run the below command to see any log output from the node process--sometimes it takes a bit to get everything built initially.

./vessel logs node

# If you wanna follow the logs live
# ./vessel logs -f node