Setting up the working environment in Docker for the yii-framework application

  • Tutorial

In order to quickly raise the working environment, there are many ways. One of them is to raise all the necessary services in Docker containers. To speed up the creation of new projects on the Yii-framework, I wrote such a small instruction that the developers in our team use.

At the start, you should have docker, docker-compose, php and php-composer.
We create the folder with the project and the docker folder in it .

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

In the docker folder, create the configuration file for our Dockerfile container .

# Базовый образ с 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

In the same docker folder, create docker-compose.yml to raise the development environment.

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

For nginx, create the docker / conf / nginx folder and the site.conf file in it. The file may change, depending on how you want to configure nginx on your project. It can be changed locally, because It connects through volume. But we must not forget to restart nginx inside the container: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;

All commands are executed from the root folder.

  • We carry out the project creation team composer create-project --prefer-dist yiisoft/yii2-app-advanced app.
  • We start an environment docker-compose -f docker/docker-compose.yml up -d
  • We initialize the project app/init --env=Development --overwrite=All
  • Open the file app / common / config / main-local.php in the editor and fill it with data to connect to the database. In the example, we have the root password as root, the DB host is db, the database name is yii-template-db.
  • Connect to the container docker exec -it docker_app_1 bash
  • We execute the database migration command php /var/www/app/yii migrate
  • Create a folder for logs mkdir /var/www/app/log
  • And go out exit
  • Brake service docker-compose -f docker/docker-compose.yml down
  • We start it again docker-compose -f docker/docker-compose.yml up -d
  • Open localhost in a browser and look at the new site.

Upd: It’s worth mentioning that there is always an official Docker image of Yii2 .

Also popular now: