Savvas Stephanides
Posted on September 12, 2024
Docker makes getting started with a new projects much easier, saving you hours of setting up individual tools for it to work. Laravel is no exception. Here's how you can set up a new Laravel project using Docker, complete with a MySQL database.
Step 1: Create a new project directory
First, we're going to set up a new empty directory, which will be houising our Laravel project. Call it myApp
or whatever else you like:
mkdir myApp
cd myApp
Step 2: Create a Docker Compose file
Next we're going to define our two containers:
One for our Laravel project which will container all the PHP code necessary.
One for the MySQL database. If you'd rather use MariaDB, replace
image: mysql:8.0
withimage: mariadb
.
services:
web:
image: bitnami/laravel
volumes:
- ./app:/app
working_dir: /app
environment:
- LARAVEL_DATABASE_HOST=db
- LARAVEL_DATABASE_USER=root
- LARAVEL_DATABASE_NAME=laravel
- LARAVEL_DATABASE_PASSWORD=pass1
- LARAVEL_DATABASE_PORT_NUMBER=3306
restart: always
ports:
- 8000:8000
db:
image: mysql:8.0
environment:
- MYSQL_ROOT_PASSWORD=pass1
- MYSQL_DATABASE=laravel
What is happening here?
Docker Compose is a tool by Docker that helps to build multiple components at the same time. Really helpful if you're running a project with multiple moving parts, like a database.
In this case, web
is the Laravel project and db
is the database. The web
container is created from the base image bitnami/laravel
, which is a handy image which has Laravel preinstalled. It adds the app
folder as a "volume" to the container so it can run it. The file gives the container the database credentials so it can connect to it, and it also exposes port 8080
so you can open the site with your browser!
The db
container is a simple container with MySQL installed. The file gives it the password for the root
user and also a name for a database so it can create it.
That's it!
Step 3: Run the containers
Now that we have our docker-compose.yml
file in place, we can give Docker the go-ahead to create both containers with a simple command:
docker compose up
Step 4: Check your site
Give it a few seconds, and your site should be up and running. You should see the following line in your terminal:
INFO Server running on [http://0.0.0.0:8000].
To open it, open http://localhost:8000 in your browser.
Success!
Enjoy your new Laravel site!
Posted on September 12, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.