Search code examples
laraveldockerubuntu

Laravel and Docker permission issue - can't save files


I already saw the solution from this post: "https://stackoverflow.com/questions/50552970/laravel-docker-the-stream-or-file-var-www-html-storage-logs-laravel-log-co

But this solution is not sufficient

The problem is that if I do what is said in the solution, i.e. to run chown -R www-data:www-data * inside the Docker container - it also changes the permission on the actual folder in the Ubuntu host, not just the container, because I set this folder in the docker-compose.yml file:

php:        
    build:
        context: ./laravel
        dockerfile: Dockerfile
    container_name: laravel
    volumes:
        - ./laravel:/var/www/html

and this is the Dockerfile:

FROM php:fpm-alpine

RUN docker-php-ext-install pdo pdo_mysql

and my user in the Ubuntu host is myuser so when I run the chown -R www-data:www-data *, myuser no longer has permissions on the host, and I can't save files.

So I either get Permission denied on the localhost URL (as seen in the other post), or I get Permission Denied to save files on VS Code on my Ubuntu host! (I am using WSL2, that's why I can use VS Code)

To sum it up:

  1. To be able to save files on my mounted volume, I have to save it as the Ubuntu user, i.e. myuser so I have to run sudo chown -R myuser ~/myproject
  2. But because certain files in Laravel expects writable permission by www-data, I can't get to my website at localhost - as seen in the post above.
  3. If I change the permissions in the Docker container using chown -R www-data:www-data /var/www/, I lose myuser permissions in the host and can't save files again, and vice versa.

Solution

  • In your docker-compose.yml file, add the user: <uid>:<gid>

    php:        
        build:
            context: ./laravel
            dockerfile: Dockerfile
        container_name: laravel
        user: "1000:1000" #type the "id" command in your terminal and look for uid and gid if you don't know what they are
        volumes:
            - ./laravel:/var/www/html
    

    This way, php-fpm will be executed as a user with these identifiers:

    • when you save a file from your host (with myuser), it will have the same identifiers as php-fpm
    • when php write a file, it will be written with the same identifiers too