Docker Compose로 Laravel의 로컬 개발 환경을 설치하고 설정하는 방법

13738 단어 laraveldockerphp

소개



이 문서에서는 Docker 및 Docker Compose를 사용하여 PHP, nginx 및 MySQL용 LEMP 환경을 구축하는 방법을 설명합니다.

전제 조건


  • 도커
  • 힘내

  • $ docker -v
    Docker version 20.10.5, build 55c4c88
    
    $ git --version
    git version 2.31.1
    


    DCT(Docker Content Trust)를 활성화하는 방법



    DCT는 Docker 이미지를 스푸핑 및 변조로부터 보호하는 보안 기능입니다.
    푸시, 빌드, 생성, 풀 또는 실행 명령이 실행될 때 자동으로 작동합니다.

    $ echo export DOCKER_CONTENT_TRUST=1 >> ~/.zshrc
    


  • https://docs.docker.com/engine/security/trust

  • 저장소


  • https://github.com/ucan-lab/docker-laravel

  • 컨테이너 구조



    애플리케이션 서버, 웹 서버 및 데이터베이스 서버로 구성된 3계층 구조입니다.

    ├── app - service running php-fpm
    ├── web - service running nginx
    └── db - service running mysql
    


    새 프로젝트를 사용하는 방법



    1 단계. 템플릿에서 새 저장소 만들기




    Use this template 을 클릭합니다.


    my-project에 대한 저장소를 만듭니다.



    템플릿 저장소를 사용하면 모든 커밋이 하나로 결합됩니다.

    2 단계. GitHub 리포지토리 복제




    $ git clone [email protected]:ucan-lab/my-project.git
    $ cd my-project
    


    3단계. 라라벨 프로젝트 생성




    $ make create-project
    


    4단계. 라라벨 환영 페이지 보여주기



    http://localhost



    5단계. 첫 번째 커밋 및 푸시




    $ git add .
    $ git commit -m "laravel install"
    $ git push -u origin HEAD
    


    기존 프로젝트를 사용하는 방법



    (선택 사항) 로컬 저장소 삭제




    $ docker-compose down -v --rmi all
    $ cd ..
    $ rm -rf my-project
    


    1 단계. GitHub 리포지토리 복제




    $ git clone [email protected]:ucan-lab/my-project.git
    $ cd my-project
    


    2 단계. 로컬 환경 초기화




    $ make init
    


    3단계. Laravel 환영 페이지 표시



    http://localhost



    Laravel의 버전을 지정하려면


    Makefile를 다시 작성하고 실행합니다.

    laravel-install:
        docker-compose exec app composer create-project --prefer-dist "laravel/laravel=6.*" .
    


    비고



    docker-compose.yml




    version: "3.9"
    volumes:
      php-fpm-socket:
      db-store:
    services:
      app:
        build:
          context: .
          dockerfile: ./infra/docker/php/Dockerfile
        volumes:
          - type: volume
            source: php-fpm-socket
            target: /var/run/php-fpm
            volume:
              nocopy: true
          - type: bind
            source: ./backend
            target: /work/backend
        environment:
          - DB_CONNECTION=mysql
          - DB_HOST=db
          - DB_PORT=3306
          - DB_DATABASE=${DB_NAME:-laravel_local}
          - DB_USERNAME=${DB_USER:-phper}
          - DB_PASSWORD=${DB_PASS:-secret}
    
      web:
        build:
          context: .
          dockerfile: ./infra/docker/nginx/Dockerfile
        ports:
          - target: 80
            published: ${WEB_PORT:-80}
            protocol: tcp
            mode: host
        volumes:
          - type: volume
            source: php-fpm-socket
            target: /var/run/php-fpm
            volume:
              nocopy: true
          - type: bind
            source: ./backend
            target: /work/backend
    
      db:
        build:
          context: .
          dockerfile: ./infra/docker/mysql/Dockerfile
        ports:
          - target: 3306
            published: ${DB_PORT:-3306}
            protocol: tcp
            mode: host
        volumes:
          - type: volume
            source: db-store
            target: /var/lib/mysql
            volume:
              nocopy: true
        environment:
          - MYSQL_DATABASE=${DB_NAME:-laravel_local}
          - MYSQL_USER=${DB_USER:-phper}
          - MYSQL_PASSWORD=${DB_PASS:-secret}
          - MYSQL_ROOT_PASSWORD=${DB_PASS:-secret}
    


    버전



    Docker Compose 파일 버전
  • https://docs.docker.com/compose/compose-file
  • https://docs.docker.com/compose/compose-file/compose-versioning/#version-3

  • Note: When specifying the Compose file version to use, make sure to specify both the major and minor numbers. If no minor version is given, 0 is used by default and not the latest minor version. As a result, features added in later versions will not be supported. For example:



    version: "3"
    


    버전: "3"

    version: "3.0"
    


    볼륨


  • https://docs.docker.com/compose/compose-file/compose-file-v3/#volumes

  • 여러 서비스에서 볼륨을 재사용하려면 최상위volumes 키로 명명된 볼륨을 정의합니다.

    서비스.*.빌드


  • https://docs.docker.com/compose/compose-file/compose-file-v3/#build

  • 서비스.*.포트


  • https://docs.docker.com/compose/compose-file/compose-file-v3/#long-syntax-1

  • 서비스.*.볼륨


  • https://docs.docker.com/compose/compose-file/compose-file-v3/#long-syntax-3

  • 서비스.*.환경


  • https://docs.docker.com/compose/compose-file/compose-file-v3/#environment

  • 앱 서비스



    ./infra/docker/php/Dockerfile




    FROM php:8.0-fpm-buster
    LABEL maintainer="ucan-lab <[email protected]>"
    SHELL ["/bin/bash", "-oeux", "pipefail", "-c"]
    
    # timezone environment
    ENV TZ=UTC \
      # locale
      LANG=en_US.UTF-8 \
      LANGUAGE=en_US:en \
      LC_ALL=en_US.UTF-8 \
      # composer environment
      COMPOSER_ALLOW_SUPERUSER=1 \
      COMPOSER_HOME=/composer
    
    COPY --from=composer:2.0 /usr/bin/composer /usr/bin/composer
    
    RUN apt-get update && \
      apt-get -y install git libicu-dev libonig-dev libzip-dev unzip locales && \
      apt-get clean && \
      rm -rf /var/lib/apt/lists/* && \
      locale-gen en_US.UTF-8 && \
      localedef -f UTF-8 -i en_US en_US.UTF-8 && \
      mkdir /var/run/php-fpm && \
      docker-php-ext-install intl pdo_mysql zip bcmath && \
      composer config -g process-timeout 3600 && \
      composer config -g repos.packagist composer https://packagist.org
    
    COPY ./infra/docker/php/php-fpm.d/zzz-www.conf /usr/local/etc/php-fpm.d/zzz-www.conf
    COPY ./infra/docker/php/php.ini /usr/local/etc/php/php.ini
    
    WORKDIR /work/backend
    



  • https://hub.docker.com/_/php
  • FROM <image>:<verion>-<variant>-<os>


  • https://laravel.com/docs/8.x/deployment#server-requirements
  • PHP >= 7.3
  • BCMath PHP 확장
  • Ctype PHP 확장
  • Fileinfo PHP 확장자
  • JSON PHP 확장
  • Mbstring PHP 확장
  • OpenSSL PHP 확장
  • PDO PHP 확장
  • 토크나이저 PHP 확장
  • XML PHP 확장


  • ./infra/docker/php/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 = ${TZ}
    
    [mysqlnd]
    mysqlnd.collect_memory_statistics = on
    
    [Assertion]
    zend.assertions = 1
    
    [mbstring]
    mbstring.language = Neutral
    


    ./infra/docker/php/php-fpm.d/zzz- www.conf




    [www]
    listen = /var/run/php-fpm/php-fpm.sock
    listen.owner = www-data
    listen.group = www-data
    listen.mode = 0666
    access.log = /dev/stdout
    


    웹 서비스



    ./infra/docker/nginx/Dockerfile




    FROM node:16-alpine as node
    FROM nginx:1.20-alpine
    LABEL maintainer="ucan-lab <[email protected]>"
    SHELL ["/bin/ash", "-oeux", "pipefail", "-c"]
    
    ENV TZ=UTC
    
    RUN apk update && \
      apk add --update --no-cache --virtual=.build-dependencies g++
    
    # node command
    COPY --from=node /usr/local/bin /usr/local/bin
    # npm command
    COPY --from=node /usr/local/lib /usr/local/lib
    # yarn command
    COPY --from=node /opt /opt
    # nginx config file
    COPY ./infra/docker/nginx/*.conf /etc/nginx/conf.d/
    
    WORKDIR /work/backend
    


  • https://hub.docker.com/_/node
  • https://hub.docker.com/_/nginx

  • ./infra/docker/nginx/default.conf




    access_log /dev/stdout main;
    error_log /dev/stderr warn;
    
    server {
        listen 80;
        root /work/backend/public;
    
        add_header X-Frame-Options "SAMEORIGIN";
        add_header X-XSS-Protection "1; mode=block";
        add_header X-Content-Type-Options "nosniff";
    
        index index.html index.htm 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 unix:/var/run/php-fpm/php-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
            include fastcgi_params;
        }
    
        location ~ /\.(?!well-known).* {
            deny all;
        }
    }
    


  • https://laravel.com/docs/8.x/deployment#nginx

  • 디비 서비스



    ./infra/docker/mysql/Dockerfile




    FROM mysql/mysql-server:8.0
    LABEL maintainer="ucan-lab <[email protected]>"
    
    ENV TZ=UTC
    
    COPY ./infra/docker/mysql/my.cnf /etc/my.cnf
    


  • https://hub.docker.com/r/mysql/mysql-server

  • ./infra/docker/mysql/my.cnf




    [mysqld]
    # default
    skip-host-cache
    skip-name-resolve
    datadir = /var/lib/mysql
    socket = /var/lib/mysql/mysql.sock
    secure-file-priv = /var/lib/mysql-files
    user = mysql
    
    pid-file = /var/run/mysqld/mysqld.pid
    
    # 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
    

    좋은 웹페이지 즐겨찾기