Search code examples
phpdockerdocker-composepermission-denied

docker-compose & dockerfile - php mkdir permission denied


I have the following docker-compose file:

version: "3.1"
services:
    www:
        build:
            context: .
            dockerfile: Dockerfile.lamp
        ports: 
            - "${WEBSERVER_PORT}:80"
        volumes:
            - ./www:/var/www/html/

As you can see, the www folder in the same folder as the docker-compose.yml file is where the web code is hosted.

I have the following dockerfile (Dockerfile.lamp):

FROM php:8.1-apache
RUN a2enmod rewrite 
RUN docker-php-ext-install pdo pdo_mysql    

# Install system dependencies
RUN apt-get update && apt-get install -y \
      git \
      libicu-dev \
      zlib1g-dev \
      g++\
      libpq-dev \
      libmcrypt-dev \
      git \
      zip \
      unzip

# Install PHP extensions
RUN docker-php-ext-install pdo_mysql
RUN docker-php-ext-install mysqli
RUN docker-php-ext-configure intl \
    && docker-php-ext-install intl

All of it works, but one issue arose that in the www/index.php file I wrote

mkdir("testFolder", 0775, true);

giving me:

Warning: mkdir(): Permission denied in /var/www/html/index.php on line 1

Neither does mkdir("testFolder"); work

I tried adding the following line to the Docker.lamp file, without success:

RUN chown -R www-data:www-data /var/www

What can I Do? I already checked:


Solution

  • One likely problem is that the directory you are mounting doesn't have the correct permissions for the www-data user inside the container to read. Running chown in the Dockerfile doesn't fix the problem because the mount doesn't exist during the build process.

    One solution is to run chown on a running instance of the container with the volume mounted:

    docker-compose run www chown -R www-data:www-data /var/www
    

    The reason running chown in the Dockerfile worked in the linked examples is because the files were being copied during the build, and then chown was being run on the copied versions.