Zebra Codes

How to use Laravel + Vite from Docker

16th of January, 2023

If you are running Laravel inside a Docker container and using Vite for Javascript/CSS bundling, you may find that the files fail to load when you view your website. You instead see one of the following errors:

  • GET http://127.0.0.1:5173/@vite/client net::ERR_CONNECTION_REFUSED
  • GET http://0.0.0.0:5173/@vite/client net::ERR_ADDRESS_INVALID

The problem occurs because by default Vite binds to the localhost address 127.0.0.1, meaning that it can only be accessed from inside the Docker container. To allow access from outside the container you can bind it to the ‘any’ IP address of 0.0.0.0 by using the server.host configuration variable. This, however, causes the website to try to connect to 0.0.0.0, which is not valid. To tell the front end to use 127.0.0.1, you must set the server.hmr.host variable.

The entire vite.config.js file is shown below:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
    server: {
        host: '0.0.0.0',
        port: 5173,
        hmr: {
            host: '127.0.0.1',
        },
    },
    plugins: [
        vue(),
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js'],
            refresh: true,
        }),
    ],
});

Remember that you will also need to expose the port in your docker-compose.yml:

version: "3.8"
name: my-laravel-project
services:
  web-server:
    ports:
      - "80:80"
      - "5173:5173"