Skip to content

Instantly share code, notes, and snippets.

@TijmenWierenga
Last active September 4, 2019 08:41
Show Gist options
  • Save TijmenWierenga/1cbd7cfdc0c5811a7c484f5bd9d2ce3b to your computer and use it in GitHub Desktop.
Save TijmenWierenga/1cbd7cfdc0c5811a7c484f5bd9d2ce3b to your computer and use it in GitHub Desktop.
PHP Dockerfile Best Practises
.dockerignore
.gitignore
.git/
vendor/
# syntax=docker/dockerfile:experimental
# Use official composer library to move the composer binary to the PHP container
FROM composer:1.6 AS composer
# Use the alpine image to create the smallest possible image
FROM php:7.3-alpine
LABEL maintainer="t.wierenga@live.nl"
# Copy the composer binary to the container
COPY --from=composer /usr/bin/composer /usr/bin/composer
# Create the project root folder and assign ownership to the pre-existing www-data user
RUN mkdir -p /var/www/html && chown -R www-data:www-data /var/www/html
# Use the pre-existing user 'www-data' for all non-root related actions
USER www-data
WORKDIR /var/www/html
# Copy just the composer dependencies to the container. This should lead to a more efficient
# build cache since the 'composer install' cache-layer should only break if one of these two
# files has changed.
COPY --chown=www-data composer.json composer.lock /var/www/html/
# Install all composer dependencies without running the autoloader and the scripts since these
# actions rely on the source files of the application.
# Also, volume mounting a bind-mounted cache to composer's /tmp folder helps speeding up the build
# since even when you break the cache by adding/removing a composer package, all previously installed
# packages are served from the mounted cache.
RUN --mount=type=cache,target=/tmp composer install --no-autoloader --no-scripts
# Copy the rest of the source code to the container. Now, if source files are changed, the cache-layer
# breaks here and the only the 'composer dump-autoload' command will have to run again.
COPY --chown=www-data . /var/www/html/
RUN composer dump-autoload --optimize
CMD ["php", "-f", "/var/www/html/app.php"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment