I tried different ways so far and saw similar questions in Stackoverflow but none worked. The problem is, that when I create a file inside the docker container, I can't edit it inside the host machine.
The project is a Laravel application with the following docker-compose file for the php
service and its docker file.
...
services:
php:
build:
context: ./dockerfiles
dockerfile: php8.1.Dockerfile
container_name: "php"
restart: unless-stopped
tty: true
networks:
- medyar_network
volumes:
- .:/var/www/html
ports:
- "${MEDYAR_PHP_PORT}:9000"
...
and Dockerfile
FROM php:8.1-fpm-alpine
RUN docker-php-ext-install pdo pdo_mysql exif
RUN apk add --no-cache pcre-dev $PHPIZE_DEPS \
&& pecl install redis \
&& docker-php-ext-enable redis.so
RUN curl -s https://getcomposer.org/installer | php -- --install-dir=/usr/bin/ --filename=composer
RUN alias composer='php /usr/bin/composer'
RUN chmod -R 755 /var/www
RUN chown -R www-data:www-data /var/www
Most of the websites suggest adding the last two lines to the Dockerfile to fix the permission, however, it doesn't work. I would appreciate it if you let me know how to fix this.
Well, thanks to the Fixing permissions issues with Docker Compose and PHP article, the problem is solved. I added the following lines to the .env
file:
UID=1000
GID=1000
which is obtained by commands
id -i
id -g
Next add the following arguments to the docker-compose
file
user_php:
build:
context: ./dockerfiles
dockerfile: php8.1.Dockerfile
args:
uid: "${UID-1000}"
gid: "${GID-1000}"
and then modify the php8.1.Dockerfile
as follows
FROM php:8.1-fpm-alpine
ARG uid
ARG gid
RUN addgroup -g ${gid} --system laravel
RUN adduser -G laravel --system -D -s /bin/sh -u ${uid} laravel
RUN sed -i "s/user = www-data/user = laravel/g" /usr/local/etc/php-fpm.d/www.conf
RUN sed -i "s/group = www-data/group = laravel/g" /usr/local/etc/php-fpm.d/www.conf
RUN apk add libpng-dev libzip-dev zip
RUN docker-php-ext-install pdo pdo_mysql gd zip
RUN apk add --no-cache pcre-dev $PHPIZE_DEPS \
&& pecl install redis \
&& docker-php-ext-enable redis.so
RUN curl -s https://getcomposer.org/installer | php -- --install-dir=/usr/bin/ --filename=composer
RUN alias composer='php /usr/bin/composer'
RUN chmod -R 755 /var/www
USER laravel
It creates a user and group with the given uid
and gid
. Then modify the user that PHP is actually running on in the container and php.ini
configuration.