前提・実現したいこと
Laradockを用いて、MongoDBとデータをやり取りするシステムをつくっています。
OS: Catalina 10.15.4
Laravel バージョン: 6.18.15
jenssegers/mongodb バージョン: 3.6
ですが、以下のエラーによりLaravelからMongoDBに接続できません。
調べても解決法がわからず、ここで質問させていただきます。
ご教授いただけると幸いです。
発生している問題・エラーメッセージ
MongoDB\Driver\Exception\ConnectionTimeoutException No suitable servers found (`serverSelectionTryOnce` set): [connection refused calling ismaster on '127.0.0.1:27017']
該当のソースコード
// プロジェクトフォルダ内の.env APP_NAME=Laravel APP_ENV=local APP_KEY=base64:SI7LRQXCmQwKkTEMHv27osBiT7k8LN+3nFQFbaVJ898= APP_DEBUG=true APP_URL=http://localhost LOG_CHANNEL=stack DB_CONNECTION=mongodb DB_HOST=127.0.0.1 DB_PORT=27017 DB_DATABASE=sample_db DB_USERNAME=root DB_PASSWORD= ...省略...
// config/database.php <?php use Illuminate\Support\Str; return [ /* |-------------------------------------------------------------------------- | Default Database Connection Name |-------------------------------------------------------------------------- | | Here you may specify which of the database connections below you wish | to use as your default connection for all database work. Of course | you may use many connections at once using the Database library. | */ 'default' => env('DB_CONNECTION', 'mysql'), /* |-------------------------------------------------------------------------- | Database Connections |-------------------------------------------------------------------------- | | Here are each of the database connections setup for your application. | Of course, examples of configuring each database platform that is | supported by Laravel is shown below to make development simple. | | | All database work in Laravel is done through the PHP PDO facilities | so make sure you have the driver for your particular database of | choice installed on your machine before you begin development. | */ 'connections' => [ 'mongodb' => [ 'driver' => 'mongodb', 'host' => env('DB_HOST', 'localhost'), 'port' => env('DB_PORT', 27017), 'database' => env('DB_DATABASE', 'sample_db'), 'username' => '', 'password' => '', 'options' => [ 'database' => '', ] ], 'sqlite' => [ 'driver' => 'sqlite', 'url' => env('DATABASE_URL'), 'database' => env('DB_DATABASE', database_path('database.sqlite')), 'prefix' => '', 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true), ], 'mysql' => [ 'driver' => 'mysql', 'url' => env('DATABASE_URL'), 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'prefix_indexes' => true, 'strict' => true, 'engine' => null, 'options' => extension_loaded('pdo_mysql') ? array_filter([ PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), ]) : [], ], ...省略... ], ];
// config/app.php ...省略... 'providers' => [ /* * Laravel Framework Service Providers... */ Illuminate\Auth\AuthServiceProvider::class, ...省略... /* * Package Service Providers... */ Jenssegers\Mongodb\Auth\PasswordResetServiceProvider::class, /* * Application Service Providers... */ App\Providers\AppServiceProvider::class, App\Providers\AuthServiceProvider::class, // App\Providers\BroadcastServiceProvider::class, App\Providers\EventServiceProvider::class, App\Providers\RouteServiceProvider::class, ], ...省略...
//モデル App/Test.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Jenssegers\Mongodb\Eloquent\ Model as MongodbModel; class Test extends MongodbModel { // protected $connection = 'mongodb'; protected $collection = 'test'; protected $fillable = [ 'phonecompany', 'model','price' ]; }
//コントローラー TestController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Test; class TestController extends Controller { public function insert(Request $request) { $product = new Test(); $product->phonecompany = $request->get('phonecompany'); $product->model = $request->get('model'); $product->price = $request->get('price'); $product->save(); return ('Phone has been successfully added'); } }
//ビュー test.blade.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Create MongoDB</title> <link rel="stylesheet" href="{{asset('css/app.css')}}"> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2 class = "text-center">Create MongoDB</h2><br/> <form method="post" action="{{route('test.store')}}"> @csrf <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="phonecompany">Phone Company:</label> <input type="text" class="form-control" name="phonecompany"> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="model">Model:</label> <input type="text" class="form-control" name="model"> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="price">Price:</label> <input type="text" class="form-control" name="price"> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> </body> </html>
実施した手順
-
Laradockをインストールして、env-exampleから.envを作成
-
.envを以下のように編集
WORKSPACE_INSTALL_MONGO = true PHP_FPM_INSTALL_MONGO=true
- コンテナをリビルド
$ docker-compose build workspace php-fpm ...省略... Step 269/269 : WORKDIR /var/www ---> Running in a1385c51232d Removing intermediate container a1385c51232d ---> 1801d0115be1 Successfully built 1801d0115be1 Successfully tagged laradock_workspace:latest ...省略... Step 152/152 : EXPOSE 9000 ---> Running in 17327899c032 Removing intermediate container 17327899c032 ---> adcb0f84addf [Warning] One or more build-args [INSTALL_CASSANDRA] were not consumed Successfully built adcb0f84addf Successfully tagged laradock_php-fpm:latest
- コンテナを立ち上げ
$ docker-compose up -d nginx mongo
- Laravelプロジェクトを作成
$ docker-compose exec workspace bash # composer create-project --prefer-dist laravel/laravel=6.* sampleproject # cd sampleproject/config # vim database.php
// 修正した内容 'connections' => [ // ------ 追加 ------- 'mongodb' => [ 'driver' => 'mongodb', 'host' => env('DB_HOST', 'localhost'), 'port' => env('DB_PORT', 27017), 'database' => env('DB_DATABASE', 'sample_db'), 'username' => env('DB_USERNAME', 'root'), 'password' => env('DB_PASSWORD'), 'options' => [ 'database' => '', ] ], // ------------------- 'sqlite' => [
- プロジェクトフォルダの.envを編集
# pwd /var/www/sampleproject # vim .env DB_CONNECTION=mongodb DB_HOST=127.0.0.1 DB_PORT=27017 DB_DATABASE=sample_db DB_USERNAME=root DB_PASSWORD=
- jenssegers/mongodb をインストール
# pwd /var/www/sampleproject # composer require jenssegers/mongodb Using version ^3.6 for jenssegers/mongodb ./composer.json has been updated ...省略... Package manifest generated successfully. 35 packages you are using are looking for funding. Use the `composer fund` command to find out more!
- mongodbコンテナにbashで入って、データベースとテーブルを作成
$ docker-compose exec mongo bash # mongo > use sample_db > db.test.insert({phonecompany:'hoge', model:'fuga', price: 10});
参考にしたURL
https://laradock.io/documentation/#use-mongo
https://github.com/jenssegers/laravel-mongodb
https://kb.objectrocket.com/mongo-db/how-to-insert-mongodb-document-using-laravel-1079
足りない情報がありましたら申し訳ございません。
回答1件
あなたの回答
tips
プレビュー