Hands-On Full Stack Web Development with Angular 6 and Laravel 5
上QQ阅读APP看书,第一时间看更新

Setting up the database inside a Docker container

It's now time to configure our database. If you use Homestead, you probably have your database connection configured and working well. To check, open your Terminal and type the following command:

php artisan tinker
DB::connection()->getPdo();

If everything goes well, you will see the following message:

Database connection message

For this example, however, we are using Docker, and we need to do some configuration to accomplish this task:

  1. Inside of the root project, open the .env file and look at line 8 (the database connection), which looks as follows:
 DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

Now, replace the preceding code with the following lines:

 DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=laravel-angular-book
DB_USERNAME=laravel-angular-book
DB_PASSWORD=123456

Note that we need to change a bit to get the Docker MySQL container directions; if you don't remember what you chose in the PHPDocker.io generator, you can copy it from the container configuration.

  1. Open docker-compose.yml at the root directory.
  2. Copy the environment variables from the MySQL container setup:
mysql:
image: mysql:8.0
entrypoint: ['/entrypoint.sh', '--character-set-server=utf8', '--
collation-server=utf8_general_ci']
container_name: larahell-mysql
working_dir: /application
volumes:
- .:/application
environment:
- MYSQL_ROOT_PASSWORD=larahell
- MYSQL_DATABASE=larahell-angular-book
- MYSQL_USER=larahell-user
- MYSQL_PASSWORD=123456
ports:
- "8083:3306"

Now, it's time to test our connection.

  1. In your Terminal window, type the following command:
docker-compose exec php-fpm bash
  1. Finally, let's check our connection; type the following command:
php artisan tinker
DB::connection()->getPdo();

You should see the same message as the previous screenshot. Then, you will have everything you need to go ahead with the example.