Laravel app through docker-compose and Nginx is resolving some assets from localhost instead of the DNS URL.
When deploying a Laravel application using Docker Compose and Nginx, you might encounter an issue where some assets are being resolved from localhost instead of the DNS URL. This can lead to broken links or other issues in your application.
The root cause of this problem is that Nginx is not able to find the static assets in the correct location. By default, Laravel serves its static assets from the public directory. However, when using Docker Compose, the public directory is not directly accessible from the web server. Instead, you need to configure Nginx to serve the static assets from the Docker container.
Here are the steps to configure Nginx to serve Laravel assets correctly:
- Create a new directory for the Laravel
publicfiles in the Docker container. For example, you can create a new directory calledapp_publicin theappvolume:
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile
volumes:
- ./app:/app
- ./app/public:/var/www/html/app_public
- ./nginx.conf:/etc/nginx/nginx.conf
ports:
- "80:80"
- "443:443"
depends_on:
- db
- php
environment:
- DB_HOST=db
- DB_DATABASE=database
- DB_USERNAME=user
- DB_PASSWORD=password
- Laravel_SAFE_MODE=false
- Laravel_DEBUG=true
command: php artisan serve --host 0.0.0.0
- Update the
nginx.conffile to serve the static assets from theapp_publicdirectory:
server {
listen 80;
server_name example.com;
location / {
try_files $uri /index.php$is_args$args;
}
location ~ \.php$ {
fastcgi_pass php:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /var/www/html/app/public$fastcgi_script_name;
include fastcgi_params;
}
location ^~ /public {
alias /var/www/html/app_public;
}
}
- Restart the Docker containers to apply the changes:
docker-compose down
docker-compose up --build
With these changes, Nginx should now be able to serve the Laravel assets correctly, without resolving them from localhost.