Home > Software engineering >  Laravel - Can't establish a second Database connection
Laravel - Can't establish a second Database connection

Time:01-05

I have a Laravel 8 project. Laravel runs on a sqlite and I want to import data from an old mariaDB Wordpress database into the sqlite. The old wordpress database is running in a docker container. And I can also access the database with MySQL Workbench.

But unfortunately I can't create the connection to the Docker database. I get the following Illuminate\Database\QueryException:

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known (SQL: select * from wp_posts where post_type = news)

Why and what am I missing here?

Here are my relevant settings:

docker-compose.yml

docker-compose.yml
version: "3.7"
services:
# ...
  #Mysl Service
  mysql:
    image: mariadb:10.5
    container_name: laravel-mysql
    volumes:
      - db_data:/var/lib/mysql
      - ./logs/mysql:/var/log/mysql
      - ./dumps/:/home/dumps
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=laravel
      - MYSQL_USER=laravel
      - MYSQL_PASSWORD=password
    ports:
      - 3307:3306
    networks:
      - mynetwork
# ...
volumes:
  db_data:

.env

DB_CONNECTION=sqlite

DB_CONNECTION_WP=mysql
DB_HOST_WP=mysql
DB_PORT_WP=3306
DB_DATABASE_WP="wordpress"
DB_USERNAME_WP=root
DB_PASSWORD_WP=password

database.php

'mysql_wp' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL_WP'),
    'host' => env('DB_HOST_WP', '127.0.0.1'),
    'port' => env('DB_PORT_WP', '3307'),
    'database' => env('DB_DATABASE_WP', 'wordpress'),
    'username' => env('DB_USERNAME_WP', 'root'),
    'password' => env('DB_PASSWORD_WP', 'password'),
    'unix_socket' => env('DB_SOCKET_WP', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
],      

service/imports/wpNewsImport.php

$data = DB::connection('mysql_wp')
  ->table('wp_posts')
  ->where("post_type", "news")
  ->get();

Thanks in advance and btw. happy new year!

CodePudding user response:

Looks like your DB_HOST_WP=mysql settings is wrong. There should be a valid DB host address or ip. If you can access the database with MySQL Workbench, than just copy host settings from it.

CodePudding user response:

I have found the problem. I am so stupid. You have to be inside the app container for the database interactions. Because the app container is in the same docker network as the database container. and i was outside. i.e. all the settings are correct. i just have to log in to the database container via bash.

docker exec -it laravel-app bash

Then it works.

  •  Tags:  
  • Related