The application is hosted in a docker container locally on my machine as I am working on the app. The php artisan migrate
command is working fine. The problem occurs when I try to load the content onto a web page using any of the Models.
Explanation below:
The Env content:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=root
DB_PASSWORD=
The migration command works.
php artisan migrate
But, when I try to display the data on a page:
public function index(){
return App\Models\User::all();
}
Laravel says:
SQLSTATE[HY000] [2002] Connection refused
My docker-compose.yml content for mysql:
services:
mysql:
image: 'mysql/mysql-server:8.0'
ports:
- '${FORWARD_DB_PORT:-3306}:3306'
environment:
MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
MYSQL_ROOT_HOST: "%"
MYSQL_DATABASE: '${DB_DATABASE}'
MYSQL_USER: '${DB_USERNAME}'
MYSQL_PASSWORD: '${DB_PASSWORD}'
MYSQL_ALLOW_EMPTY_PASSWORD: 1
volumes:
- 'sail-mysql:/var/lib/mysql'
- './vendor/laravel/sail/database/mysql/create-testing-database.sh:/docker-entrypoint-initdb.d/10-create-testing-database.sh'
networks:
- sail
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-p${DB_PASSWORD}"]
retries: 3
timeout: 5s
When I change DB_HOST to the name of the container;
DB_HOST=mysql
Laravel starts to display the data, but php artisan migrate
does not work.
How it tries to connect to it:
PDO::__construct("mysql:host=mysql;port=3306;dbname=my_db", "root", "", [])
Then fails:
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo for mysql failed: No such host is known. (SQL: SHOW FULL TABLES WHERE table_type = 'BASE TABLE')
I need to understand why it is doing so, and how I can resolve this problem. I would also like to know if this will have the same problem when I deploy the application on production.
Thank you.