Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why composer.json file from volume directory is not visible in composer install command run in dockerfile?

docker-compose.yml:

version: '3.3'
services:
    web:
        image: nginx:latest
        ports:
            - "8080:80"
        volumes:
            - ./api:/var/www/html/api
            - ./site.conf:/etc/nginx/conf.d/default.conf
        links:
            - php
    php:
        build:
            context: ./docker
            dockerfile: php.Dockerfile
        volumes:
        - ./api:/var/www/html/api
        links:
            - db
    db:
       image: mysql:5.7 
       environment:
         MYSQL_ROOT_PASSWORD: password
         MYSQL_DATABASE: symfony
         MYSQL_USER: symfony
         MYSQL_PASSWORD: symfony
       ports:
         - "9906:3306"

php.Dockerfile:

FROM php:7-fpm
WORKDIR /var/www/html/api
COPY --from=composer /usr/bin/composer /usr/bin/composer
RUN apt-get update && apt-get upgrade -y \
    && apt-get install -y git libzip-dev unzip \
    && docker-php-ext-install \
        pdo_mysql zip \
    && docker-php-ext-enable \
        pdo_mysql zip \
    && composer install \
    && bin/console make:migration

Error from an output of command: docker-compose build --no-cache:

Composer could not find a composer.json file in /var/www/html/api

However when I'm inside PHP container using docker exec -it sf4_php_1 bash

I see that composer.json file is in /var/www/html/api and I'm able to run composer install properly.

What I'm doing wrong?

like image 899
Codium Avatar asked Jan 25 '23 05:01

Codium


1 Answers

The volume is mounted at runtime, not at build time.

When you are building the image, there is no composer.json in there because your volume has not been mounted yet.

Before you run composer install you will need to copy all the necessary files for the build process.

E.g. a better Dockerfile would be something like this:

(in this case I'm bringing some Symfony files, since this is copied from a Symfony image)

COPY --from=composer /usr/bin/composer /usr/bin/composer

RUN apt-get update && apt-get upgrade -y \
    && apt-get install -y git libzip-dev unzip \
    && docker-php-ext-install \
        pdo_mysql zip \
    && docker-php-ext-enable \
        pdo_mysql zip

RUN mkdir -p /var/www/html/api
WORKDIR /var/www/html/api

COPY composer.json composer.lock symfony.lock .env.dist ./

RUN composer install \
    && bin/console make:migration

This not only will actually work, but generate different layers for the building of your application and the installation of the platform requirements. With this, changes in composer.json would not trigger reinstalling the PHP extensions and updating apt.

like image 181
yivi Avatar answered Jan 28 '23 11:01

yivi