Running composer install within a Dockerfile

This took a lot of digging for someone new to Docker :) Thanks to @iurii-drozdov for pointing me in the right direction with the comment about the docker-compose.yml.

In my docker-compose.yml, I was mounting my host working dir into /var/www/html. This happened after the build. So composer ran the install, installed all the dependencies correctly on build, and then, when running docker-compose up, I was mounting my host dir into the container and wiping all those changes out.

The solution was to run composer install after mounting the volume. It's straight forward enough to do this by simply exec'ing into the container after bringing it up - running composer and any other package managers - then finally running the web server.

However, I found a neater solution. I changed my final CMD in the Dockerfile to:

CMD bash -c "composer install && php artisan serve --host 0.0.0.0 --port 5001"

This will run composer install and bring up the web server as a final part of the docker-compose up.

Credit for the solution here: Docker - Execute command after mounting a volume


You can also use the official dockerhub composer image.

This is an example of a multi-stage build with composer running first in a separate container. The resulting /app/vendor is copied to wherever you want in your final image.

FROM composer as builder
WORKDIR /app/
COPY composer.* ./
RUN composer install
...
FROM php:7.1-fpm-alpine
...
COPY --from=builder /app/vendor /var/www/vendor

If you don't want to have the command in the Dockerfile, we found that the simplest way was to add this to our docker-compose file:

composer_installation:
  container_name: composer_installation
  image: composer
  volumes:
    - ./:/app
  command: composer install --ignore-platform-reqs

The update is a bit slow, probably because it is syncing with the PHP container.