Goal dari multi stage build ini:
Langsung aja, bikin project Laravel pakai composer dan masuk ke dalam direktori projek:
# setup project
composer create-project laravel/laravel laravel9-example
# masuk direktori
cd laravel9-example
# bikin .dockerignore
touch .dockerignore
# bikin Dockerfile
touch Dockerfile
Kemudian siapkan file-file berikut:
.dockerignore
.git/
.gitattributes
.gitignore
.editorconfig
.env.example
vendor/
node_modules/
Dockerfile
Dockerfile
# Install laravel deps
FROM composer:2 as vendor
RUN mkdir -p /var/www/laravel
WORKDIR /var/www/laravel
COPY database/ ./database/
COPY composer.* ./
RUN composer install \
--ignore-platform-reqs \
--no-interaction \
--no-plugins \
--no-scripts \
--prefer-dist
# Build asset
FROM node:16-alpine as asset
RUN mkdir -p /var/www/laravel/public
WORKDIR /var/www/laravel
COPY package*.json ./
RUN npm install
COPY vite.config.js ./
COPY resources/ resources/
RUN npm run build
FROM php:8.1-apache
ENV APACHE_DOCUMENT_ROOT /var/www/laravel/public
RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf
RUN sed -ri -e 's!/var/www/!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf
RUN mkdir -p /var/www/laravel && chown www-data:www-data /var/www/laravel
WORKDIR /var/www/laravel
COPY --chown=www-data:www-data . .
COPY --chown=www-data:www-data --from=vendor /var/www/laravel/vendor/ ./vendor/
COPY --chown=www-data:www-data --from=asset /var/www/laravel/public/build/ ./public/build/
USER www-data:www-data
Build container image
docker build -t sumarsono/laravel:v9 .
Test run container
docker run -d --rm --name laravel9 sumarsono/laravel:v9