i dockerized my laravel project (9.25.1) and my problem is my query in tinker totally works and php artisan migrate
works too but when i query in controller i get mysql error SQLSTATE[HY000] [2002] Connection refused
Dockerfile:
FROM php:8.1-fpm-alpine
RUN docker-php-ext-install pdo pdo_mysql sockets
RUN curl -sS https://getcomposer.org/installer | php -- \
--install-dir=/usr/local/bin --filename=composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
WORKDIR /app
COPY . .
RUN composer install
docker-composer.yml:
version: '3.8'
services:
main:
build:
context: .
dockerfile: Dockerfile
command: 'php artisan serve --host=0.0.0.0'
volumes:
- .:/app
ports:
- 8000:8000
db:
platform: linux/x86_64
image: mysql:8.0
environment:
MYSQL_DATABASE: main
MYSQL_USER: admin
MYSQL_ROOT: admin
MYSQL_PASSWORD: admin
MYSQL_ROOT_PASSWORD: root
volumes:
- ./storage/dbdata:/var/lib/mysql
ports:
- 4306:3306
.env:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=4306
DB_DATABASE=main
DB_USERNAME=admin
DB_PASSWORD=admin
My Answer:
The issue you are facing is likely due to the way you are trying to connect to the MySQL database from your Laravel controller. Since your Laravel application is running inside a Docker container, you should not use `127.0.0.1` as the DB_HOST in your .env file. Instead, you should use the service name of the MySQL container defined in your docker-compose.yml file.
In your case, the service name for the MySQL container is `db`, so you should update your .env file as follows:
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=main
DB_USERNAME=admin
DB_PASSWORD=admin
By using the service name `db` as the DB_HOST, your Laravel application will be able to connect to the MySQL database running in the `db` container.
After updating your .env file, try running your Laravel application again and see if the connection to the MySQL database is successful.
Rate this post
5 of 5 based on 2394 votesComments