Unable to Connect Laravel to MySQL in Docker - Database Not Found Error
To help you connect Laravel to your MySQL database in Docker and resolve the "Database Not Found" error, follow the steps below:
-
Ensure Docker and Docker Compose are installed: Make sure you have Docker and Docker Compose installed on your system. You can download Docker from the official website (https://www.docker.com/) and Docker Compose from the GitHub repository (https://github.com/docker/compose).
-
Create a
docker-compose.yml
file: In your Laravel project directory, create a new file nameddocker-compose.yml
. Add the following content to the file:version: '3.8' services: app: build: . container_name: my_laravel_app ports: - "8000:80" volumes: - .:/app - /app/storage:/app/storage - /app/bootstrap/cache:/app/bootstrap/cache - /app/public:/var/www/html environment: - DB_HOST=db - DB_DATABASE=laravel_db - DB_USERNAME=laravel_user - DB_PASSWORD=laravel_password - MAIL_MAILER=smtp - MAIL_HOST=smtp.gmail.com - MAIL_PORT=587 - [email protected] - MAIL_PASSWORD=your_email_password - APP_KEY=base64:<your_app_key> depends_on: - db db: image: mysql:8.0 container_name: my_laravel_db ports: - "3306:3306" volumes: - db_data:/var/lib/mysql environment: - MYSQL_ROOT_PASSWORD=laravel_db_password - MYSQL_DATABASE=laravel_db - MYSQL_USER=laravel_user - MYSQL_PASSWORD=laravel_password volumes: db_data:
Replace
<your_app_key>
with your Laravel application key. -
Update Laravel
.env
file: Open the.env
file in your Laravel project directory and update the following variables:DB_HOST=db DB_DATABASE=laravel_db DB_USERNAME=laravel_user DB_PASSWORD=laravel_password
-
Build and run the Docker containers: In your terminal, navigate to your Laravel project directory and run the following command to build and start the containers:
docker-compose up --build
This command will build the Laravel application image and start the containers for the Laravel application and MySQL database.
-
Verify the connection: Once the containers are running, you can verify the connection by accessing the Laravel application in your web browser or by running the following command in your terminal:
php artisan db:connect
If the connection is successful, you should see a message like "PDO::__construct: Successfully connected".
If you still encounter the "Database Not Found" error, make sure that your database and application containers are running and that the database container is accessible from the application container. You can check the logs of the containers using the following command:
docker-compose logs
This command will display the logs of all the containers in your project. Look for any error messages related to the database connection and investigate further to resolve the issue.