To create a production-ready php-fpm-alpine Docker image for Laravel, you can start with the official php:alpine image and then install the necessary extensions and dependencies required by Laravel. Below is a Dockerfile example that outlines the steps to achieve this:
# Use the official PHP image as a base
FROM php:8.1-fpm-alpine
# Set working directory
WORKDIR /var/www
# Install system dependencies
RUN apk --no-cache add \
build-base \
libpng-dev \
libjpeg-turbo-dev \
libwebp-dev \
libxpm-dev \
freetype-dev \
libzip-dev \
zip \
unzip \
git \
bash \
fcgi \
libmcrypt-dev \
oniguruma-dev \
postgresql-dev
# Clear cache
RUN rm -rf /var/cache/apk/*
# Install PHP extensions
RUN docker-php-ext-configure gd --with-freetype --with-jpeg --with-webp \
&& docker-php-ext-install gd \
&& docker-php-ext-install pdo pdo_mysql pdo_pgsql mbstring zip exif pcntl bcmath opcache
# Install Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
# Copy existing application directory contents
COPY . /var/www
# Copy existing application directory permissions
COPY --chown=www-data:www-data . /var/www
# Change current user to www
USER www-data
# Expose port 9000 and start php-fpm server
EXPOSE 9000
CMD ["php-fpm"]
Explanation:
-
Base Image: We start with the
php:8.1-fpm-alpineimage, which is a lightweight version of PHP with FPM (FastCGI Process Manager). -
Working Directory: Set the working directory to
/var/www. -
System Dependencies: Install necessary system dependencies using
apk. These include libraries for image processing, zip handling, and other utilities. -
Clear Cache: Remove the APK cache to reduce the image size.
-
PHP Extensions: Install required PHP extensions for Laravel. This includes extensions for database handling, image processing, and other functionalities.
-
Composer: Copy Composer from the official Composer image to the current image.
-
Application Code: Copy the application code to the working directory and set the appropriate permissions.
-
User: Change the current user to
www-datafor security reasons. -
Expose Port: Expose port 9000, which is the default port for PHP-FPM.
-
CMD: Start the PHP-FPM server.
Building the Docker Image
To build the Docker image, navigate to the directory containing your Dockerfile and run:
docker build -t laravel-php-fpm-alpine .
Running the Docker Container
To run the Docker container, use the following command:
docker run -p 9000:9000 -v $(pwd):/var/www laravel-php-fpm-alpine
This setup should give you a much smaller Docker image compared to the default Laravel image, while still including all necessary dependencies and extensions for running a Laravel application.