Docker deployment in Laravel - Mini Project: Build & Apply
Dockerfile in your Laravel project root. Write these exact lines to set up PHP 8.1 with Composer and copy your app code:
FROM php:8.1-fpm
RUN docker-php-ext-install pdo pdo_mysql
COPY . /var/www/html
WORKDIR /var/www/html
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN composer install
Use the official PHP 8.1 FPM image. Install the pdo_mysql extension for database support. Copy your Laravel app code into the container. Set the working directory. Install Composer and run composer install to get dependencies.
docker-compose.yml in your project root. Add a version key set to '3.8'. Define two services: app and db. For app, use the Dockerfile you created, map port 8000 to container port 9000, and mount the current directory to /var/www/html. For db, use the mysql:8.0 image, set environment variables MYSQL_ROOT_PASSWORD to secret and MYSQL_DATABASE to laravel, and expose port 3306. Your docker-compose.yml should look like this structure:Use build: . to build the app service from your Dockerfile. Map ports so you can access Laravel on localhost:8000. Mount your code so changes update live. Use the official MySQL 8 image for the database with environment variables for root password and database name.
.env file. Change the database connection settings to match the Docker MySQL service. Set DB_HOST to db, DB_PORT to 3306, DB_DATABASE to laravel, DB_USERNAME to root, and DB_PASSWORD to secret. Your changes should look like this:
DB_HOST=db
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=secretSet DB_HOST to the service name db so Laravel connects to the MySQL container. Use the same database name, username, and password as in docker-compose.yml.
app service in docker-compose.yml to start the PHP built-in server on port 9000 serving the Laravel public folder. Add this line under app::
command: php artisan serve --host=0.0.0.0 --port=9000
This will let you access your Laravel app at http://localhost:8000.Use the command key in docker-compose.yml under the app service to start Laravel's built-in server listening on all interfaces at port 9000.