How to Configure Multiple Database Connections in a Laravel Project Using Docker
This tutorial walks you through creating a dedicated folder, setting up environment and Docker‑Compose files, defining Laravel, MySQL, and PostgreSQL services, and launching containers so you can reliably connect to multiple databases from a Laravel application.
In this tutorial we guide you step‑by‑step to configure multiple database connections in a Laravel project using Docker, explaining both the practical commands and the underlying integration between Docker and Laravel’s database settings.
Step 1: Create a new folder in the Laravel project to store Docker and configuration files. For example:
mkdir myFolderStep 2: Create new environment and configuration files inside myFolder . Add a .env file to define variables such as DB_PORT , DB_USERNAME , and DB_HOST . Also create a docker-compose.yml file to describe Docker services, networks, and volumes.
Step 3: Docker Compose configuration – open the docker-compose.yml file and add service definitions for the Laravel app, MySQL, and PostgreSQL, ensuring the environment variables match those in the .env file. Example:
version: '3.8'
services:
app:
image: laravel:latest
container_name: laravel_app
ports:
- "8000:8000"
volumes:
- .:/var/www/html
depends_on:
- mysql
- postgres
mysql:
image: mysql:5.7
container_name: mysql_db
environment:
MYSQL_ROOT_PASSWORD: rootpassword
MYSQL_DATABASE: laravel_db1
MYSQL_USER: user
MYSQL_PASSWORD: password
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
postgres:
image: postgres:13
container_name: postgres_db
environment:
POSTGRES_DB: laravel_db2
POSTGRES_USER: user
POSTGRES_PASSWORD: password
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
mysql_data:
postgres_data:Step 4: Start Docker containers by navigating to the directory containing docker-compose.yml and running:
docker-compose up -dVerify that the containers are running with:
docker psStep 5: Connect the databases to a client such as Dbvear (or any other database management tool) using the credentials defined in the .env file.
Step 6: Test the connections by executing queries to ensure the Laravel application can communicate with each database without issues.
Conclusion – By following these steps you have successfully used Docker to configure multiple database connections for a Laravel project, improving the organization, manageability, and flexibility of your development environment.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.