docker-compose로 심포니 5 환경을 만들려고했습니다.

저는 공부용으로 한 것입니다. 실수 등 있으면 가르쳐 주시면 감사합니다.

↓이쪽에도 설정을 준비했습니다


docker-compose.yml
version: "3"

services:
  web:
    image: nginx
    ports:
      - "8080:80"
    volumes:
      # ホストのdefault.confを同期
      - ./default.conf:/etc/nginx/conf.d/default.conf
      # ホストの./myappフォルダを同期
      - ./myapp:/var/www/html/myapp
    depends_on:
      - php

  php:
    build: .
    volumes:
      # ホストの./myappフォルダを同期
      - ./myapp:/var/www/html/myapp

  db:
    image: mysql:8.0
    # PDOでhostを指定するときにこのコンテナ名を使う
    container_name: mysql
    volumes:
      # データが消えてしまわないようにマウントmysqlのフォルダをマウント
      - ./mysql:/var/lib/mysql
    # MySQL8.0でのデフォルトの認証方式が「caching_sha2_password」なので変更する
    # 設定しないと "The server requested authentication method unknown to the client" とエラーになる
    command: --default-authentication-plugin=mysql_native_password
    environment:
      # 設定必須、rootパスワード
      - MYSQL_ROOT_PASSWORD=root
      # この設定はオプション、イメージの起動時に作成されるデータベース名
      - MYSQL_DATABASE=sample

default.conf
server {
    server_name  localhost;
    root /var/www/html/myapp/public;

    location / {
        index  index.php index.html;
        try_files $uri $uri/ /index.php;
    }

    location ~ \.php$ {
       fastcgi_pass   php:9000;
       fastcgi_index  index.php;
       fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
       include        fastcgi_params;
    }
}

Dockerfile
FROM php:7.4-fpm

RUN apt-get update \
    && apt-get install -y zlib1g-dev libzip-dev \
    && docker-php-ext-install pdo pdo_mysql zip

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

WORKDIR /var/www/html/myapp
$ docker-compose up -d
$ docker-compose exec php pwd #カレントディレクトリのパスを確認
/var/www/html/myapp
$ docker-compose exec php composer create-project symfony/website-skeleton . #myappフォルダにsymfonyのプロジェクト作成

symfony 버전을 지정하려면 composer create-project symfony/website-skeleton:^5.1 .
http://localhost-8080.com/ 에서 symfony 화면이 표시됩니다.



데이터베이스 확인
.env 파일 수정

myapp/.env
- DATABASE_URL=mysql://db_user:[email protected]:3306/db_name?serverVersion=5.7
+ DATABASE_URL=mysql://root:root@mysql:3306/sample?serverVersion=8.0
$ docker-compose exec php php bin/console make:controller ProductController #コントローラ作成
src/Controller/ProductController.php 생성됨

http://localhost:8080/product에 액세스하면 컨트롤러 내용이 표시됩니다.



공식 ( Databases and the Doctrine ORM (Symfony Docs) )대로 Entity를 작성해보고 접속할 수 있는 확인해 본다
$ docker-compose exec php php bin/console make:entity

 Class name of the entity to create or update (e.g. GrumpyJellybean):
 > Product

 created: src/Entity/Product.php
 created: src/Repository/ProductRepository.php

 Entity generated! Now let's add some fields!
 You can always add more fields later manually or by re-running this command.

 New property name (press <return> to stop adding fields):
 > name

 Field type (enter ? to see all types) [string]:
 > string

 Field length [255]:
 > 255 

 Can this field be null in the database (nullable) (yes/no) [no]:
 > no

 updated: src/Entity/Product.php

 Add another property? Enter the property name (or press <return> to stop adding fields):
 > price

 Field type (enter ? to see all types) [string]:
 > integer

 Can this field be null in the database (nullable) (yes/no) [no]:
 > no

 updated: src/Entity/Product.php

 Add another property? Enter the property name (or press <return> to stop adding fields):
 > 



  Success! 


 Next: When you're ready, create a migration with php bin/console make:migration

src/Entity/Product.phpsrc/Repository/ProductRepository.php가 생성됨
$ docker-compose exec php php bin/console make:migration #migrationファイル作成



  Success! 


 Next: Review the new migration "migrations/Version20200715184046.php"
 Then: Run the migration with php bin/console doctrine:migrations:migrate
 See https://symfony.com/doc/current/bundles/DoctrineMigrationsBundle/index.html

migrations/Version20200715184046.php
$ docker-compose exec php php bin/console doctrine:migrations:migrate #migration実行

 WARNING! You are about to execute a database migration that could result in schema changes and data loss. Are you sure you wish to continue? (yes/no) [yes]:
 > yes

[notice] Migrating up to DoctrineMigrations\Version20200715184046
[notice] finished in 266.3ms, used 18M memory, 1 migrations executed, 1 sql queries

↑ 마이그레이션이 실행되었습니다.

ProductController 수정 수정

src/Controller/ProductController.php
  <?php
  namespace App\Controller;


+ use App\Entity\Product;
  use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  use Symfony\Component\Routing\Annotation\Route;

  class ProductController extends AbstractController
  {
    /**
     * @Route("/product", name="product")
     */
     public function index()
     {
+        // 保存
+        $entityManager = $this->getDoctrine()->getManager();
+        $product = new Product();
+        $product->setName('Keyboard');
+        $product->setPrice(1999);
+        $entityManager->persist($product);
+        $entityManager->flush();
+
+        // 取得
+        $id = 1;
+        $product = $this->getDoctrine()
+            ->getRepository(Product::class)
+            ->find($id);
+        if (!$product) {
+            throw $this->createNotFoundException(
+                'No product found for id '.$id
+            );
+        }
+        dd($product);

         return $this->render('product/index.html.twig', [
             'controller_name' => 'ProductController',
         ]);
     }

데이터베이스에서 데이터를 가져 왔는지 확인



끝까지 봐 주셔서 감사합니다 m (_ _) m

참고
  • Docker에 Composer를 설치하는 모범 사례 (및 설명) - Qiita
  • docker-php-ext-install zip fails #61
  • 좋은 웹페이지 즐겨찾기