[For beginners] Laravel Docker AWS (EC2) How to easily deploy Web application (PHP) from 0 (free) ②-Docker development environment construction-

0. Overview

** I say it many times, but please google the moment you come across a word you don't know! !! !! !! !! ** ** The whole picture of ① is here, so I wonder if it will be easier to understand after reading this! !! !! https://qiita.com/SG_Sg/items/6b8ce48567b6b6602805  To be more specific, the red part to be created this time qiita-square

Create a Laravel (PHP) project using Dokcer (docker description)

Well, I want to build an environment using Docker specifically, but ... ** "What is Docker?" "What are the benefits of using Docker?" "How do you use it at the development site?" ** It's full of doubts, so let's give a rough explanation! (At first, no matter how much I googled, I didn't really understand what I was saying.) What is Docker? ?? Please google for details such as ...

1. Benefits of Docker, why professional engineers use it

① You can create an environment, a project, and a program without polluting the MAC! What do you mean? ?? ?? Let's see what happens if you create a project in ** without using Docker **! !! qiita-square The version is different like this and it depends on the environment of other PCs! !!

** Use Docker ** Let's see what happens when you create a project! !! qiita-square

If you use Docker, you can install the environment in Docker and put the whole project on github. ** Because I will install the necessary environment in Docker ** ** You don't have to install the required environment on your Mac! !! ** **

2. First of all, prepare various things (install Git or Docker, etc.)

I'm using the default terminal below! ** ① Create a github account ** https://github.com ** ② Initial setting of Git ** Excuse me. .. Googling with "Mac git Preferences" Sweat It is ok if the following is finally displayed.

MacBook-Pro% git config --list | grep user
user.name=[githubname]
user.email=67626524+[githubname]@users.noreply.github.com

** ③ Github SSH connection settings ** This is also googled with "Mac Github SSH connection"! ** If you get an error, go around the error statement again! !! !! ** **

MacBook-Pro% ssh -T github.com
Hi [github name]! You've successfully authenticated, but GitHub does not provide shell access.

If the word "successfully" appears like this, you can almost go!

** ④ Install docker, docker-compose (the one that can be started and stopped) ** Install Docker for Mac https://docs.docker.com/docker-for-mac/install ** Installation confirmation (If you install something, make sure it is installed!) **

MacBook-Pro% docker --version
Docker version 20.10.0, build 7287ab3
MacBook-Pro% docker-compose --version
docker-compose version 1.27.4, build 40524192

** Docker startup confirmation ** スクリーンショット 2021-01-10 15.42.16.png You should be ready! !!

3. Create a Docker project! !!

3-1. Until github operation check

** ① Create a project (directory) ** I created "Laravel Projext" in my home directory and created a "docker-test" directory in it! !! Feel free to do this! !! !!

MacBook-Pro % mkdir LaravelProject
MacBook-Pro % cd LaravelProject
MacBook-Pro LaravelProject % mkdir docker-test
MacBook-Pro LaravelProject % cd docker-test 
MacBook-Pro docker-test % 

** ② Create a remote repository ** Let's google how to make it with "Giuhub remote repository creation"! !! Create "Docker Laravel Test Project" スクリーンショット 2021-01-10 16.04.20.png

** ② Test push to remote repository! Check if Git is working **

//README.Create md file
MacBook-Pro docker-test % echo "README import First" >> README.md
//Allow git management
MacBook-Pro docker-test % git init
//Add to staging!
MacBook-Pro docker-test % git add . 
//commit! !!
MacBook-Pro docker-test % git commit -m "first commit README"
//Push destination remote repository to Github! !! (Connect with SSH * URL is SSH)
MacBook-Pro docker-test % git remote add origin [email protected]:SugiKoki/DockerLaravelTestProject.git
//Check the remote repository destination! It's definitely a github project
MacBook-Pro docker-test % git remote -v
origin	[email protected]:SugiKoki/DockerLaravelTestProject.git (fetch)
origin	[email protected]:SugiKoki/DockerLaravelTestProject.git (push)
//Check git branch
MacBook-Pro docker-test % git branch
* master
//git branch (master)Push to
MacBook-Pro docker-test % git push -u origin master
kokisugi@sugihirokinoMacBook-Pro docker-test % 

** ③ Check with VScode ** スクリーンショット 2021-01-10 16.58.18.png Make sure it is written in the directory! !! Now you can work! !! !! !!

3-2. Confirmation of final goal

The file structure aims to look like this! !! スクリーンショット 2021-01-10 17.06.23.png The inside of the backend is where you actually program! !!

3-3. Create (insert) application server (app)

** ① Create docker-compose.yml **

MacBook-Pro docker-test % touch docker-compose.yml

** Open the directory with VScode and do the following ** qiita-square ** The following is the content **

version: "3.8"
services:
  app:
    build: ./infra/php
    volumes:
      - ./backend:/work
  web:
    image: nginx:1.18-alpine
    ports:
      - 10080:80
    volumes:
      - ./backend:/work
      - ./infra/nginx/default.conf:/etc/nginx/conf.d/default.conf
    working_dir: /work
  db:
    build: ./infra/mysql
    volumes:
      - db-store:/var/lib/mysql
volumes:
  db-store:

** The above app is the application server The web in the middle is the web server The db below is the database server **

Set the environment you want to create here and install it on Docker according to this! !! !!

** ②. Create /docker/php/Dockerfile **

MacBook-Pro docker-test % mkdir -p infra/php
MacBook-Pro docker-test % touch infra/php/Dockerfile

Put the code below into Dockerfile. スクリーンショット 2021-01-10 17.28.12.png

FROM php:7.4-fpm-buster
SHELL ["/bin/bash", "-oeux", "pipefail", "-c"]

ENV COMPOSER_ALLOW_SUPERUSER=1 \
  COMPOSER_HOME=/composer

COPY --from=composer:1.10 /usr/bin/composer /usr/bin/composer

RUN apt-get update && \
  apt-get -y install git unzip libzip-dev libicu-dev libonig-dev && \
  apt-get clean && \
  rm -rf /var/lib/apt/lists/* && \
  docker-php-ext-install intl pdo_mysql zip bcmath

COPY ./php.ini /usr/local/etc/php/php.ini

WORKDIR /work

What you are doing here ** Installing Composer commands Required for Laravel Install bcmath, pdo_mysql is missing **

** ③. Create /docker/php/Dockerfile **

MacBook-Pro docker-test % touch infra/php/php.ini

スクリーンショット 2021-01-10 17.35.52.png

Put the following code into php.ini

zend.exception_ignore_args = off
expose_php = on
max_execution_time = 30
max_input_vars = 1000
upload_max_filesize = 64M
post_max_size = 128M
memory_limit = 256M
error_reporting = E_ALL
display_errors = on
display_startup_errors = on
log_errors = on
error_log = /dev/stderr
default_charset = UTF-8

[Date]
date.timezone = Asia/Tokyo

[mysqlnd]
mysqlnd.collect_memory_statistics = on

[Assertion]
zend.assertions = 1

[mbstring]
mbstring.language = Japanese

3-4. Create (insert) a web server (web)

** ① Create docker/nginx/default.conf **

MacBook-Pro docker-test % mkdir infra/nginx
MacBook-Pro docker-test % touch infra/nginx/default.conf

スクリーンショット 2021-01-10 17.44.41.png Paste the code below! !!

server {
    listen 80;
    server_name example.com;
    root /work/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass app:9000;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

3-5. Create (insert) database (db) server

** ①. Create /docker/mysql/Dockerfile **

MacBook-Pro docker-test % mkdir infra/mysql
MacBook-Pro docker-test % touch infra/mysql/Dockerfile

スクリーンショット 2021-01-10 17.58.18.png

Paste the code below!

FROM mysql:8.0

ENV MYSQL_DATABASE=sg_db \
  MYSQL_USER=sg \
  MYSQL_PASSWORD=sg \
  MYSQL_ROOT_PASSWORD=sg \
  TZ=Asia/Tokyo

COPY ./my.cnf /etc/mysql/conf.d/my.cnf
RUN chmod 644 /etc/mysql/conf.d/my.cnf

This is optional, so you can love it! Because it's the name and password used to connect the database Let's remember not to forget!

  MYSQL_USER=sg \
  MYSQL_PASSWORD=sg \
  MYSQL_ROOT_PASSWORD=sg \

** ② Create docker/mysql/my.cnf **

MacBook-Pro docker-test % touch infra/mysql/my.cnf

スクリーンショット 2021-01-10 17.59.49.png

Paste the code below

[mysqld]
# character set / collation
character_set_server = utf8mb4
collation_server = utf8mb4_0900_ai_ci

# timezone
default-time-zone = SYSTEM
log_timestamps = SYSTEM

# Error Log
log-error = mysql-error.log

# Slow Query Log
slow_query_log = 1
slow_query_log_file = mysql-slow.log
long_query_time = 1.0
log_queries_not_using_indexes = 0

# General Log
general_log = 1
general_log_file = mysql-general.log

[mysql]
default-character-set = utf8mb4

[client]
default-character-set = utf8mb4

This completes 3 containers! !! !! !! Did you have a solid final directory structure? ?? ??

3-6. Start Docker! (Check the contents)

** ① Use it when you want to run docker! ** **

MacBook-Pro docker-test % docker-compose up -d --build
・ ・ ・ ・
Successfully built 9813d5181de8
Successfully tagged docker-test_db:latest
Creating docker-test_app_1 ... done
Creating docker-test_db_1  ... done
Creating docker-test_web_1 ... done
MacBook-Pro docker-test % 

If you get done with the above feeling, they are OK! ** ・ Check how it works while it is moving! ** **

MacBook-Pro docker-test % docker-compose ps
      Name                     Command               State           Ports        
----------------------------------------------------------------------------------
docker-test_app_1   docker-php-entrypoint php-fpm    Up      9000/tcp             
docker-test_db_1    docker-entrypoint.sh mysqld      Up      3306/tcp, 33060/tcp  
docker-test_web_1   /docker-entrypoint.sh ngin ...   Up      0.0.0.0:10080->80/tcp

By the way, if you want to restart, if you want to stop once, down!

MacBook-Pro docker-test % docker-compose down
//Once stopped, let's start again
MacBook-Pro docker-test % docker-compose up -d --build

** How to check the version of each server (container) put in Docker **

・ App server

MacBook-Pro docker-test %  docker-compose exec app bash
//PHP version check
root@5ce9c9fa1435:/work# php -V
//Check the version of composer
root@5ce9c9fa1435:/work# composer -v
//Check the list of installed extensions
root@5ce9c9fa1435:/work# php -m
//Get out of docker
root@5ce9c9fa1435:/work# exit 

・ Web server

MacBook-Pro docker-test % docker-compose exec web nginx -v

・ DB server

MacBook-Pro docker-test % docker-compose exec db bash
//Check the version of mysql
root@6bcf6de7e31e:/# mysql -V
//Get out of docker
root@6bcf6de7e31e:/work# exit 

** This completes the Docker environment construction! !! !! Now let's put in Laravel and program! !! !! ** **

*** You should do Git commits on a regular basis! *** ***

MacBook-Pro docker-test % git add .
MacBook-Pro docker-test % git commit -m  "laravel commit"
MacBook-Pro docker-test % git push

3-7. Install Laravel (do it on the app server)

** ① Enter app and install Laravel **

MacBook-Pro docker-test % docker-compose exec app bash
root@5ce9c9fa1435:/work# composer create-project --prefer-dist "laravel/laravel=8.*" .
//laravel version check
root@5ce9c9fa1435:/work# php artisan -V
Laravel Framework 8.21.0
root@5ce9c9fa1435:/work# exit 

** ② Laravel welcome screen display ** http://127.0.0.1:10080 Access to! !! !! スクリーンショット 2021-01-10 18.41.21.png ・ If you check VScode, it should look like this backend! スクリーンショット 2021-01-10 18.44.21.png

3-8. Try programming! !! (Check if you can create and display html, blade.php files!)

Let's display HTML (.blade.php)! !! We will proceed with the MVC model!

** ① In backend/resources/views Create hello directory Create hello.blade.php in hello directory **

スクリーンショット 2021-01-10 18.53.45.png The contents are this. You can paste it!

<html>
    <body>
        <h1>HELLO Larabel<h1>
    </body>
</html>

** ② Set the controller to call from the URL! ** ** -Modified backend/routes/web.php スクリーンショット 2021-01-10 21.01.54.png Add the following code to backend/routes/web.php!

/// URL/Call "HelloController" when hello
Route::get('hello', 'App\Http\Controllers\HelloController@index');

** ③ In backend/app/http/Controllers / Create HelloController.php ** スクリーンショット 2021-01-10 21.06.24.png Put the following code in backend/app/http/Controllers / Add to HelloController.php!

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\KrononUser;
use Faker\Provider\ar_JO\Person;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class HelloController extends Controller
{
    public function index()
    {
        return view('hello.hello');
    }
}

** ④ Access the URL and display it! !! !! ** ** http://127.0.0.1:10080/hello スクリーンショット 2021-01-10 21.45.34.png

3-9. Try connecting to the database! !! !! !!

** Modify the DB connection settings in backend/.env on the source code. ** ** スクリーンショット 2021-01-10 21.54.15.png ** ① Change to the following code! !! While matching the time when the DB server was made! ** **

DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=sg_db
DB_USERNAME=sg
DB_PASSWORD=sg

スクリーンショット 2021-01-10 21.57.32.png ** ② Change backend/.env.example in the same way **

DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=sg_db
DB_USERNAME=sg
DB_PASSWORD=sg

By the way, when you git clone it, it will work if you do it from here

** ③ Laravel installation **

Various after entering the app container

MacBook-Pro docker-test % docker-compose exec app bash
//Install composer
root@36ffabe3ffc9:/work# composer install
//.env.example.Copy to env file
root@36ffabe3ffc9:/work# cp .env.example .env
//You can generate an application key with this command.
root@36ffabe3ffc9:/work# php artisan key:generate
Application key set successfully.

//Execute the migration that is included by default! !! The default table is reflected in the DB
root@36ffabe3ffc9:/work# php artisan migrate
Migration table created successfully.
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (40.88ms)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table (37.06ms)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated:  2019_08_19_000000_create_failed_jobs_table (35.00ms)

This is the default, but the DB now has tables and more! !!

** ④ Check database (default) **

MacBook-Pro docker-test % docker-compose exec db bash 
//Log in to mysql with the set USER
root@d94d20dd2212:/# mysql -u sg -p
//Enter the set PASSWORD.I wrote it in env! !!
Enter password: 
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| sg_db              |
+--------------------+
2 rows in set (0.01 sec)
mysql> use sg_db
Database changed
mysql> show tables;
+-----------------+
| Tables_in_sg_db |
+-----------------+
| failed_jobs     |
| migrations      |
| password_resets |
| users           |
+-----------------+

** ⑤ Create a migration and reflect it in the app! !! ** ** スクリーンショット 2021-01-11 13.51.27.png **/backend/database/migration/2021_01_03_090902_create_people_table.php Create **

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePeopleTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('people', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('mail');
            $table->integer('age');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('people');
    }
}

** ⑥ Execute migration (app container) and execute! ** ** It does not reach the DB container in docker unless it is in the app

MacBook-Pro docker-test % docker-compose exec app bash
root@36ffabe3ffc9:/work# php artisan migrate
Migrating: 2021_01_03_090902_create_people_table
Migrated:  2021_01_03_090902_create_people_table (49.03ms)

** ⑦ Create Seeder! !! First, from DatabaseSeeder.php in the default ** "What is Seeder?" ** Dummy data. You can put data in the database just by executing a command! !! ** ** スクリーンショット 2021-01-11 14.37.11.png Paste the following source into DatabaseSeeder.php

$this->call(PeopleTableSeeder::class);

** Create PeopleTableSeeder.php on the called side ** スクリーンショット 2021-01-11 14.40.27.png Paste the following source into PeopleTableSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class PeopleTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $param = [
            'id' => 1,
            'name' => 'test',
            'mail' => 'test',
            'age' => 20,
        ];
	DB::table('people')->insert($param);
    }
    
}

** ⑧ Execute Seeder! ** **

MacBook-Pro docker-test % docker-compose exec app bash
root@36ffabe3ffc9:/work# php artisan db:seed
Seeding: Database\Seeders\PeopleTableSeeder
Seeded:  Database\Seeders\PeopleTableSeeder (29.08ms)
Database seeding completed successfully.

Now you have a table and dummy data! The rest is perfect if you display it on the web! !!

Display the data registered in the database

** ① Create views/hello.blade.php ** スクリーンショット 2021-01-11 14.49.15.png Modify the following source hello.blade.php

<html>
    <body>
        <h1>HELLO Larabel<h1>
            <h1>I'm displaying from the DB<h1>
            <tr><th>Name</th><th>Mail</th><th>Age</th></tr>
                <br>
                @foreach ($items as $item)
                <tr>
                    <td>{{$item -> name}}</td>
                    <td>{{$item -> mail}}</td>
                    <td>{{$item -> age}}</td>
                </tr>
            @endforeach
    </body>
</html>

** ② Change Controllers/HelloController.php ** スクリーンショット 2021-01-11 14.50.24.png Change to the following source

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\KrononUser;
use Faker\Provider\ar_JO\Person;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class HelloController extends Controller
{
    public function index()
    {
        $items = DB::table('people')->get();
        return view('hello.hello',['items' => $items]);
    }
}

** ③ Access the created app! !! ** ** http://127.0.0.1:10080/hello スクリーンショット 2021-01-11 14.53.14.png With this, it would be perfect if the dummy data entered in the DB Seeder was displayed! !! !! Finally commit and finish! !! !!

MacBook-Pro docker-test % git add .
MacBook-Pro docker-test % git commit -m "db complete"
MacBook-Pro docker-test % git push

After that, it's OK if you can use AWS to release this to the world !!! Stay tuned next time! !!

Thank you for your hard work

I'm pretty tired of building this kind of environment, isn't it? Click here to see the big picture [For beginners] Laravel Docker AWS (EC2) How to easily deploy a web application (PHP) from 0 (free) ①-Overview- https://qiita.com/SG_Sg/items/6b8ce48567b6b6602805 Next time ③ [For beginners] Laravel Docker AWS (EC2) How to easily deploy a web application (PHP) from 0 (free) ③-Deploy to EC2- I am planning.

References

[Super Introduction] Docker Hands-on to build a Laravel development environment at explosive speed in 20 minutes https://qiita.com/ucan-lab/items/56c9dc3cf2e6762672f4 The article by ↑ is insanely easy to understand, and it is written in detail, so please refer to this as well. Especially, the information of the initial default settings is wonderful. Upward compatible with this article.

Recommended Posts

[For beginners] Laravel Docker AWS (EC2) How to easily deploy Web application (PHP) from 0 (free) ②-Docker development environment construction-
[For beginners] Laravel Docker AWS (EC2) How to easily deploy a web application (PHP) from 0 (free) ①-Overview-
How to publish an application using AWS (3) EC2 instance environment construction
How to migrate a web application created in a local docker environment to AWS
Web application development environment construction in Java (for inexperienced people)
Environment construction for Servlet application development
Environment construction with Docker for beginners
Deploy SpringBoot application to AWS EC2
Ruby on Rails --From environment construction to simple application development on WSL2
PostgreSQL environment construction with Docker (from setup to just before development)
Laravel development environment construction with Docker (Mac)
How to build a Ruby on Rails environment using Docker (for Docker beginners)
Creating a java web application development environment with docker for mac part1
Create a java web application development environment with docker for mac part2
How to find OSS trends for web development
How to link Rails6 Vue (from environment construction)
Temporarily move Docker environment from Mac to AWS
From building an AWS cloud environment to deploying a Spring Boot app (for beginners)
How to check the WEB application created in the PC development environment on your smartphone
How to quit Docker for Mac and build a Docker development environment with Ubuntu + Vagrant
[For beginners] Until building a Web application development environment using Java on Mac OS
JavaFX application development with IntelliJ IDEA and Gradle ~ From environment construction to sample code ~
How to deploy to Heroku from a local docker image
BEAR application Docker development environment construction example (docker-sync, Mutagen)
How to build docker environment with Gradle for intelliJ
Deploy laravel using docker on EC2 on AWS ① (Create EC2 instance)
List how to learn from Docker to AKS on AWS
Build Docker + Laravel PHP + Vue.js development environment in 5 minutes
Java development for beginners to start from 1-Vol.1-eclipse setup
How to make Laravel faster with Docker for Mac
How to use GitHub for super beginners (team development)
Deploy laravel using docker on EC2 on AWS ② (Elastic IP acquisition-linking)
Beginners install docker for mac and prepare php7.0 operating environment
How to create an application server on an EC2 instance on AWS
[Procedure 1 for beginners] Ruby on Rails: Construction of development environment
From studying programming for 2 months to releasing a web application
Deploy laravel using docker on EC2 on AWS ④ (git clone ~ deploy, migration)
Java web application development environment construction with VS Code (struts2)
Rails application development environment construction with Docker [Docker, Rails, Puma, Nginx, MySQL]
How to build Rails, Postgres, ElasticSearch development environment with Docker
How to install Web application for each language in Nginx
[Docker context] ~ How to access docker in remote environment from VScode ~
How to deploy a Rails application on AWS (article summary)
Connect to AWS RDS from your local PC Docker environment
Procedure for migrating Rails application development environment to Docker even if you are inexperienced (Rails5 + MySQL8.0 + docker-compose)
What I was addicted to when updating the PHP version of the development environment (Docker) from 7.2.11 to 7.4.x
Deploy with EC2 / Docker / Laravel
Deploy laravel using docker on EC2 on AWS ③ (SSH connection ~ Docke-compose installation)
Procedure for building a Rails application development environment with Docker [Rails, MySQL, Docker]
How to install Pry after building Rails development environment with Docker
How to create a web server on an EC2 instance on AWS
Build a web application development environment that uses Java, MySQL, and Redis with Docker CE for Windows