Dockerizing laravel application with nginx and php-fpm
To Dockerize a Laravel application with Nginx and PHP-FPM, you'll need to create several Dockerfiles and configuration files. Here's a step-by-step guide to help you get started:
-
Create a new Laravel project:
composer create --prefer-dist laravel/laravel project-name -
Create a new directory for your Dockerfiles and configuration files:
mkdir docker cd docker -
Create a
Dockerfilefor your Laravel application:touch DockerfileOpen the
Dockerfilein your favorite text editor and add the following content:FROM php:7.4-fpm-alpine RUN apk add --no-cache --update \ zip \ unzip \ curl \ git \ && docker-php-ext-install pdo pdo_mysql zip \ && apk del apk --purge \ && rm -rf /var/cache/apk/* WORKDIR /var/www/html COPY . /var/www/html RUN chmod -R 775 /var/www/html EXPOSE 9000 CMD ["php-fpm"]This Dockerfile uses the PHP 7.4 FPM Alpine image as the base image and installs the necessary dependencies and extensions for Laravel. It also sets the working directory to
/var/www/htmland copies the contents of the current directory to that location. -
Create a
Dockerfilefor Nginx:touch nginx.DockerfileOpen the
nginx.Dockerfilein your favorite text editor and add the following content:FROM nginx:alpine COPY nginx.conf /etc/nginx/nginx.conf COPY . /usr/share/nginx/html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]This Dockerfile uses the Nginx Alpine image as the base image and copies the
nginx.conffile and the contents of the current directory to the Nginx HTML directory. -
Create a
nginx.conffile:touch nginx.confOpen the
nginx.conffile in your favorite text editor and add the following content:worker_processes 1; events { worker_connections 1024; } server { listen 80; server_name localhost; location / { index-index.php index.php; try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { fastcgi_pass php:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /var/www/html$fastcgi_script_name; include fastcgi_params; } }This configuration file sets up Nginx to listen on port 80 and serve PHP files using the PHP-FPM server running on port 9000.
-
Build the Docker images:
docker build -t project-name . docker build -t project-name-nginx . -
Run the Docker containers:
docker run -d --name project-name-php project-name-php docker run -d --name project-name-nginx -p 80:80 project-name-nginx --link project-name-php:phpThis command starts the PHP container and the Nginx container, and links the PHP container to the Nginx container so that Nginx can communicate with PHP-FPM.
-
Access your Laravel application: Open a web browser and navigate to
http://localhost. You should see your Laravel application running.
That's it! You've successfully Dockerized your Laravel application with Nginx and PHP-FPM. This setup provides a lightweight and portable environment for running your Laravel application.