Yii2 php fpm docker

Installation ¶

The minimum requirement by this project template is that your Web server supports PHP 5.6.0.

Installing using Composer ¶

If you do not have Composer, follow the instructions in the Installing Yii section of the definitive guide to install it.

With Composer installed, you can then install the application using the following commands:

composer create-project --prefer-dist yiisoft/yii2-app-advanced yii-application 

The command installs the advanced application in a directory named yii-application . You can choose a different directory name if you want.

It uses asset-packagist for managing bower and npm package dependencies through Composer. Also you can use asset-plugin, as in earlier versions, but it works slowly.

Install from an Archive File ¶

Extract the archive file downloaded from yiiframework.com to a directory named advanced that is directly under the Web root.

Then follow the instructions given in the next subsection.

Preparing application ¶

After you install the application, you have to conduct the following steps to initialize the installed application. You only need to do these once for all.

    Open a console terminal, execute the init command and select dev as environment.

/path/to/php-bin/php /path/to/yii-application/init 
/path/to/php-bin/php /path/to/yii-application/init --env=Development --overwrite=All --delete=All 
  • for frontend /path/to/yii-application/frontend/web/ and using the URL http://frontend.test/
  • for backend /path/to/yii-application/backend/web/ and using the URL http://backend.test/

For Apache it could be the following:

  ServerName frontend.test DocumentRoot "/path/to/yii-application/frontend/web/"  # use mod_rewrite for pretty URL support RewriteEngine on # If a directory or a file exists, use the request directly RewriteCond % !-f RewriteCond % !-d # Otherwise forward the request to index.php RewriteRule . index.php # use index.php as index file DirectoryIndex index.php # . other settings. # Apache 2.4 Require all granted ## Apache 2.2 # Order allow,deny # Allow from all   ServerName backend.test DocumentRoot "/path/to/yii-application/backend/web/"  # use mod_rewrite for pretty URL support RewriteEngine on # If a directory or a file exists, use the request directly RewriteCond % !-f RewriteCond % !-d # Otherwise forward the request to index.php RewriteRule . index.php # use index.php as index file DirectoryIndex index.php # . other settings. # Apache 2.4 Require all granted ## Apache 2.2 # Order allow,deny # Allow from all   
 server < charset utf-8; client_max_body_size 128M; listen 80; ## listen for ipv4 #listen [::]:80 default_server ipv6only=on; ## listen for ipv6 server_name frontend.test; root /path/to/yii-application/frontend/web/; index index.php; access_log /path/to/yii-application/log/frontend-access.log; error_log /path/to/yii-application/log/frontend-error.log; location / < # Redirect everything that isn't a real file to index.php try_files $uri $uri/ /index.php$is_args$args; > # uncomment to avoid processing of calls to non-existing static files by Yii #location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ # try_files $uri =404; #> #error_page 404 /404.html; # deny accessing php files for the /assets directory location ~ ^/assets/.*\.php$ < deny all; > location ~ \.php$ < include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass 127.0.0.1:9000; #fastcgi_pass unix:/var/run/php5-fpm.sock; try_files $uri =404; > location ~* /\. < deny all; > > server < charset utf-8; client_max_body_size 128M; listen 80; ## listen for ipv4 #listen [::]:80 default_server ipv6only=on; ## listen for ipv6 server_name backend.test; root /path/to/yii-application/backend/web/; index index.php; access_log /path/to/yii-application/log/backend-access.log; error_log /path/to/yii-application/log/backend-error.log; location / < # Redirect everything that isn't a real file to index.php try_files $uri $uri/ /index.php$is_args$args; > # uncomment to avoid processing of calls to non-existing static files by Yii #location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ # try_files $uri =404; #> #error_page 404 /404.html; # deny accessing php files for the /assets directory location ~ ^/assets/.*\.php$ < deny all; > location ~ \.php$ < include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass 127.0.0.1:9000; #fastcgi_pass unix:/var/run/php5-fpm.sock; try_files $uri =404; > location ~* /\. < deny all; > > 
127.0.0.1 frontend.test 127.0.0.1 backend.test 
Thank you for registration. Please check your inbox for verification email. 
  • delete soft line breaks ‘=’ and newlines to create a single line with the line below
  • change ‘=3D’ to ‘=’
  • On Mac / Linux, convert \r\n to \n — MIME CRLF line breaks are «real» and should be preserved.

Paste this URL into a browser tab to complete the User creation. You will be presented with the message: Your email has been confirmed!

Note: if you want to run advanced template on a single domain so / is frontend and /admin is backend, refer to Using advanced project template at shared hosting.

Installing using Vagrant ¶

This way is the easiest but long (~20 min).

This installation way doesn’t require pre-installed software (such as web-server, PHP, MySQL etc.) — just do next steps!

Manual for Linux/Unix users ¶

git clone https://github.com/yiisoft/yii2-app-advanced.git cd yii2-app-advanced/vagrant/config cp vagrant-local.example.yml vagrant-local.yml 

That’s all. You just need to wait for completion! After that you can access project locally by URLs:

Manual for Windows users ¶

  1. Install VirtualBox
  2. Install Vagrant
  3. Reboot
  4. Create GitHub personal API token
  5. Prepare project:
    • download repo yii2-app-advanced
    • unzip it
    • go into directory yii2-app-advanced-master/vagrant/config
    • copy vagrant-local.example.yml to vagrant-local.yml
  6. Place your GitHub personal API token to vagrant-local.yml
  7. Open terminal ( cmd.exe ), change directory to project root and run command:

That’s all. You just need to wait for completion! After that you can access project locally by URLs:

Installing using Docker ¶

Install the application dependencies

docker-compose run --rm backend composer install 

Initialize the application by running the init command within a container

docker-compose run --rm backend php /app/init 

Adjust the components[‘db’] configuration in common/config/main-local.php accordingly.

 'dsn' => 'mysql:host=mysql;dbname=yii2advanced', 'username' => 'yii2advanced', 'password' => 'secret', 

Docker networking creates a DNS entry for the host mysql available from your backend and frontend containers.

If you want to use another database, such a Postgres, uncomment the corresponding section in docker-compose.yml and update your database connection.

 'dsn' => 'pgsql:host=pgsql;dbname=yii2advanced', 

For more information about Docker setup please visit the guide.

docker-compose run --rm backend yii migrate 

Access it in your browser by opening

Источник

Настройка рабочего окружения в Docker для yii-framework приложения

Для того чтобы быстро поднять рабочее окружение существует много способов. Один из них — поднять все необходимые сервисы в Docker-контейнерах. Чтобы ускорить создание новых проектов на Yii-framework я написал такую небольшую инструкцию, которую используют разработчики в нашей команде.

На старте у вас должны стоять docker, docker-compose, php и php-composer.
Создаем папку с проектом и в ней папку docker.

mkdir project-dir cd project-dir && mkdir docker

В папке docker создаем файл конфигурации нашего контейнера Dockerfile.

# Базовый образ с nginx и php FROM richarvey/nginx-php-fpm # Добавляем наше веб приложение ADD app /var/www/app # Удаляем конфиги сайтов которые там есть RUN rm -Rf /etc/nginx/sites-enabled/* # Добавляем наш конфиг ADD docker/conf/nginx/site.conf /etc/nginx/sites-available/site.conf # Включаем его RUN ln -s /etc/nginx/sites-available/site.conf /etc/nginx/sites-enabled/site.conf

В этой же папке docker создаем docker-compose.yml для поднятия окружения разработки.

# Последняя версия docker-compose version: '3' # Создаем общую сеть deafult для всех контейнеров networks: default: driver: bridge # Создаем отдельные контейнеры services: # Контейнер с веб-приложением app: # Собираем из Dockerfile build: # Корнем указываем корень основного проекта context: ../ dockerfile: ./docker/Dockerfile # Показываем наружу 80 порт ports: - "80:80" # Подключаем к общей сети с другими контейнерами networks: - default # Запускаем только после db depends_on: - db # Линкуем внешнюю папку с исходниками внутрь volumes: - "../app:/var/www/app" # Так же линкуем конфиг для nginx - "./conf/nginx:/etc/nginx/sites-available" # Контейнер с базой данных db: image: mysql:latest # Подключаем к общей сети с другими контейнерами networks: - default # Показываем наружу порт ports: - "3336:3306" # Задаем параметры для инициализации БД environment: # Пароль к БД MYSQL_ROOT_PASSWORD: root # Создаваемая по умолчанию бд MYSQL_DATABASE: yii-template-db # Линкуем внешнюю папку для хранения БД volumes: - "./database:/var/lib/mysql"

Для nginx создаем папку docker/conf/nginx и файл site.conf в ней. Файлик может изменяться, в зависимости от того, как вы хотите настроить nginx на своем проекте. Его можно менять локально, т.к. он подключается через volume. Но надо не забывать внутри контейнера перезагружать nginx: nginx -s reload

server < charset utf-8; client_max_body_size 128M; listen 80; ## listen for ipv4 root /var/www/app/frontend/web/; index index.php; access_log /var/www/app/log/frontend-access.log; error_log /var/www/app/log/frontend-error.log; location / < try_files $uri $uri/ /index.php$is_args$args; ># uncomment to avoid processing of calls to non-existing static files by Yii #location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ < # try_files $uri =404; #>#error_page 404 /404.html; # deny accessing php files for the /assets directory location ~ ^/assets/.*\.php$ < deny all; >location ~ \.php$ < include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass unix:/var/run/php-fpm.sock; try_files $uri =404; >location ~* /\. < deny all; >>

Все команды выполняются из корневой папки.

  • Выполняем команду создания проекта composer create-project —prefer-dist yiisoft/yii2-app-advanced app .
  • Запускаем окружение docker-compose -f docker/docker-compose.yml up -d
  • Инициализируем проект app/init —env=Development —overwrite=All
  • Открываем в редакторе файл app/common/config/main-local.php и заполняем его данными для подключения к БД. В примере у нас пароль root — root, хост БД — db, имя БД — yii-template-db.
  • Подключаемся к контейнеру docker exec -it docker_app_1 bash
  • Выполняем команду миграции БД php /var/www/app/yii migrate
  • Создаем папку для логов mkdir /var/www/app/log
  • И выходим exit
  • Тормозим сервис docker-compose -f docker/docker-compose.yml down
  • Запускаем его заново docker-compose -f docker/docker-compose.yml up -d
  • Открываем localhost в браузере и смотрим на новый сайт.

Upd: Обязательно стоит упомянуть, что всегда есть официальный Docker-образ Yii2.

Источник

Читайте также:  Roboto web font css
Оцените статью