Setting up Laravel with Docker and Docker Compose is an excellent way to create a consistent development environment. Docker simplifies app deployment by packaging everything needed, from code to libraries, in isolated containers, so your Laravel app can run smoothly on any system. With Docker, developers can avoid the common “it works on my machine” problem by ensuring that everyone’s development setup is the same. Laravel, one of the most popular PHP frameworks, is great for building robust web applications, and pairing it with Docker makes it even easier to manage and deploy.
In this guide, we’ll walk you through setting up Laravel using a Dockerfile and Docker Compose. The Dockerfile helps define the app’s environment, while Docker Compose makes it easy to manage multiple containers, like the web server, PHP, and database.
Prerequisites
- Docker installed on your system.
- Docker-compose installed on your system.
- Basic understanding of Docker concepts such as images, containers, and Dockerfile.
Step 1: Setting up Laravel
Start by creating a new Laravel project or navigating to your existing project.
composer create-project --prefer-dist laravel/laravel my-laravel-app
cd my-laravel-app
Step 2: Create a Dockerfile
The Dockerfile contains instructions to Docker for building your app’s environment.
Let’s create a file named Dockerfile in your project root directory and add the following:
Step 3: Docker-compose Configuration
Docker-compose helps in defining and running multi-container Docker applications. Create a docker-compose.yml file in the project root:
Step 4: Nginx Configuration
The Docker-compose uses Nginx web server for running the application.
Create a new folder nginx in your project root. Inside, create a file named default.conf with the following content:
Step 5: Start the Docker Containers
With everything set up, start your containers:
docker-compose up -d
Once the containers are up, you can visit http://localhost:8000 in your browser to view your Laravel application.
Step 6: Running Artisan Commands
To run Laravel’s Artisan commands (like migrations), you need to execute them inside the container.
Use the following command to access the Laravel container:
docker-compose exec app bash
Now you can run any Artisan command, such as:
php artisan migrate
This will run the migrations and set up the tables in your MySQL database.
Step 7: Cleanup
To stop the services, you can use:
docker-compose down
Conclusion
By integrating Laravel with Docker and Docker-compose, developers can ensure a consistent environment throughout development, testing, and production stages. This not only eases the deployment process but also eradicates the common “it works on my machine” problem. As you become more accustomed to Docker, you can further enhance and customize this setup to suit your specific needs.