Multi-stage Dockerization of LARAVEL Application

Multi-stage Dockerization of LARAVEL Application

Multi-stage Docker builds are helpful for apps like Laravel, where some files are only needed during building but not in the final image. These builds make the final Docker image smaller and more efficient. Here's an example of making a multi-stage Dockerfile for a Laravel app:

# Stage 1: Build the Laravel application
FROM composer:2 AS builder

# Set the working directory
WORKDIR /app

# Copy only the composer files to leverage caching
COPY composer.json composer.lock ./

# Install the dependencies
RUN composer install --no-interaction --no-plugins --no-scripts --prefer-dist

# Copy the rest of the application code
COPY . .

# Generate the optimized autoloader
RUN composer dump-autoload --optimize --no-dev --classmap-authoritative

# Generate any necessary assets
RUN php artisan key:generate
RUN php artisan config:cache

# Stage 2: Create the final runtime image
FROM php:7.4-apache

# Set the working directory
WORKDIR /var/www/html

# Copy the application code from the builder stage
COPY --from=builder /app .

# Set permissions (adjust as needed)
RUN chown -R www-data:www-data storage bootstrap/cache
RUN chmod -R 775 storage bootstrap/cache

# Expose port 80
EXPOSE 80

# Start the Apache web server
CMD ["apache2-foreground"]

Explanation:

  • Stage 1 (Builder):

    • Use the official composer image as the builder stage to install Laravel dependencies and generate optimized autoloader.

    • Copy only the composer.json and composer.lock files first to leverage Docker caching when dependencies haven't changed.

    • Copy the rest of the application files.

    • Generate necessary assets, like keys and configuration cache.

  • Stage 2 (Runtime):

    • Use a minimal PHP-Apache base image for the final runtime.

    • Copy the application code from the builder stage, excluding unnecessary files.

    • Set appropriate permissions on Laravel's storage and bootstrap/cache directories.

    • Expose port 80 and start the Apache web server.

To build the Docker image, run:

docker build -t your-laravel-app .

This Dockerfile is based on a typical Laravel app structure. Change the versions, settings, and permissions to fit your particular Laravel app needs. Also, remember to check the Laravel documentation, especially if your app needs extra setup or has special steps for the Dockerization process.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!