Access your Laravel Valet sites and proxies from your Docker containers
Laravel Valet gives you the ability to access a local app with a custom domain name. You may create a folder which is parked in the Valet configuration and all subfolders will be a associated with a custom domain. Valet also offers the ability to proxy a local service to a domain of your choice.
Development with Docker containers
Sometimes you build your entire app as multiple Docker containers like frontend, api, backend. You may use Docker Compose to run your containers locally which could be something like this (minimal example) :
version: "3.8"
services:
frontend:
build:
context: ./frontend
volumes:
- './frontend/:/var/www/html:cached'
ports:
- 3000:3000
api:
build:
context: ./api
volumes:
- './api/:/var/www/html:cached'
ports:
- 8081:80
backend:
build:
context: ./backend
volumes:
- './backend/:/var/www/html:cached'
ports:
- 8082:80
As per this configuration you will be able to reach your containers like this
- frontend : http://localhost:3000
- api : http://localhost:8081
- backend : http://localhost:8082
With proxy
You may proxy your Docker services :
valet proxy frontend.my-app http://localhost:3000 --secure
valet proxy api.my-app http://localhost:8081 --secure
valet proxy backend.my-app http://localhost:8082 --secure
Now you may access your containers like this
- frontend : https://frontend.my-app.test
- api : https://api.my-app.test
- backend : https://backend.my-app.test
The frontend may access the api using https://api.my-app.test
which will work if the frontend makes api calls in the browser.
How about Server-side rendering?
At this time your containers can reach other services by their name (e.g. api, backend, frontend). But they can't resolve Valet domains. So if your frontend container makes api calls to https://api.my-app.test
the request will fail.
Short answer
You may use the loopback
command with an unreachable private IP address.
valet loopback 10.254.254.254
Long anwser
Valet uses DnsMasq to proxy all requests to *.test
. By default DnsMasq and Nginx are configured to listen to the default loopback network interface address 127.0.0.1
. When a container resolves a Valet site/proxy it gets the 127.0.0.1
address which refers to itself and not the host machine.
The loopback interface may have aliases, so we can add an alias using an unreachable private IP address (e.g. 10.254.254.254
). DnsMasq and Nginx will listen to this address and when a container will resolve a Valet site/proxy it will get the 10.254.254.254
address which refer to the host machine.
The Valet loopback
command gives you the ability to set the loopback alias address you want.
Now you can access any of your Valet sites/proxies from both your host machine and your Docker containers.
Et voilà!