Docker – Bind for 0.0.0.0:6379 failed: port is already allocated

To see what process are running on a port, you can use the bellow:
sudo lsof -i :6379

This command result something like this:

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
docker-pr 36176 root 4u IPv4 1116895 0t0 TCP *:6379 (LISTEN)
docker-pr 36183 root 4u IPv6 1117458 0t0 TCP *:6379 (LISTEN)


Then we can kill process by process ID as follows:
sudo kill -9 36176
sudo kill -9 36183

You are done. Happy Coding!

Identified by password and grant all privileges for database to a user

In mysql 8, first you need to create a user, then you can grant previleges:

Use this command (update as per your ip):
CREATE USER 'root'@'172.25.0.2' IDENTIFIED BY 'root1234'; GRANT SELECT ON *.* TO 'root'@'172.25.0.2';
If you need to update authentication method from caching_sha2_password to 
mysql_native_password.

Use this command:
ALTER USER 'root'@'172.25.0.2' IDENTIFIED WITH mysql_native_password BY 'root1234';

Import mysql database from localhost to the database inside docker

To import we can use docker cp command like below:

docker cp /home/sharetrip/Downloads/sample_database_latest.sql 4ab2b1296c56:/sample_database_latest.sql

It will successfully copy the file inside docker

Then you can go inside docker

docker exec -it 4ab2b1296c56 bin/bash

After that, inside docker container you can run the bellow command to import the database.

mysql -u root -p sample_database < sample_database_latest.sql

Congrats!. You have imported the database inside docker

Install and use of docker in ubuntu

Install Docker:

Update the package index:
sudo apt-get update

Install necessary dependencies:
sudo apt-get install -y apt-transport-https ca-certificates curl software-properties-common

Add the Docker GPG key:
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg


Set up the stable Docker repository:
echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null


Install Docker:
sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io


Add your user to the docker group to run Docker without sudo:
sudo usermod -aG docker $USER


Verify Docker installation:
docker --version

Install Docker Compose:

Download the Docker Compose binary:
sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

Make the Docker Compose binary executable:
sudo chmod +x /usr/local/bin/docker-compose

Verify Docker Compose installation:
docker-compose --version

Start docker service with daemon and check the status of service:

sudo systemctl daemon-reload
sudo systemctl status docker

Add file upload to tinymce in yii2

$uploadFileJs = 'function uploadFile(callback, value, meta) {
        $("#fileupload").trigger("click");
      
        $("#fileupload").on("change", function () {
            var reader = new FileReader();       
            var formData = new FormData();
            var file = this.files[0];
            formData.append("file", file);

            var fileName = "";        
            $.ajax({
                url: base_url + "/blog-post/upload-file",
                type: "post",
                data: formData,  
                processData: false,
                contentType: false,
                async: false,
                success: function (response) {
                    fileName = response;
                }
            });

            reader.onload = function (e) {            
                callback(fileName);
            };
            reader.readAsDataURL(file);
        });
};';

$this->registerJs($uploadFileJs);

<div class="row">
    <div class="col-md-12">
        <?= $form->field($model, 'content')->widget(TinyMce::class, [
            'language' => 'en_GB',
            'clientOptions' => [
                'plugins' => [
                    "advlist autolink lists link charmap print preview",
                    "searchreplace visualblocks code fullscreen wordcount",
                    "insertdatetime media image table contextmenu paste autoresize",
                    "emoticons"
                ],
                'toolbar' => "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist | link image",
                'branding' => false, // To show or not who powered (TinyMCE label)
                'resize' => 'both',
                'file_picker_callback' => new JsExpression('uploadFile')
            ]
        ]); ?>
        <input type='file' name='fileupload' id='fileupload' style='display: none;'>
    </div>
</div>

Add it to controller for ajax action

public function actionUploadFile()
{
    $uploadedFile = UploadedFile::getInstanceByName('file');
    echo $this->processUploadedImage($uploadedFile, 'uploads/tinymce-files/', true);
}

private static function processUploadedImage($file, $dir)
 { 
      if (!file_exists($dir)) {
          mkdir($dir, 0755);
      }  
     $filename = Yii::$app->security->generateRandomString() . '.' . $file->extension;     
     if ($file->saveAs($dir . $filename)) {} return false;
 }

Add tool to tinymce editor in yii2

$infoToolbarJs = '$(function() {
    $(\'#country_to_data\').click(function() {
         var data = $("#country_to option:selected").text();     
         if(data != "Select country") {
            tinymce.activeEditor.execCommand("mceInsertContent", false, \'<flight to="\' + data + \'"/>\');
            $("#country_to").modal("hide");
            $.pjax.reload({container: "#country_to_container", async: false});
         }
    });
    
    $("#close-btn-flight").click(function() {
         $.pjax.reload({container: "#country_to_container", async: false});
    });
})';
$this->registerJs($infoToolbarJs);


<div class="row">
    <div class="col-md-12">
        <?= $form->field($model, 'content')->widget(TinyMce::class, [
            'language' => 'en_GB',
            'clientOptions' => [
                'plugins' => [
                    "advlist autolink lists link charmap print preview",
                    "searchreplace visualblocks code fullscreen wordcount",
                    "insertdatetime media image table contextmenu paste autoresize",
                    "emoticons"
                ],
                'toolbar' => "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist | link image infoto",
                'branding' => false, // To show or not who powered (TinyMCE label)
                'external_plugins' => [
                    'infoto' => '/library/js/tinymce.plugin.js'                    
                ],
                'resize' => 'both'                
            ]
        ]); ?>       
    </div>
</div>

Modal::begin([
    'header' => '<h4 class="modal-title">Add country</b></h4>',
    'options' => [
        'id' => 'country_to',
        'tabindex' => false, // important for Select2 to work properly
    ],
    'footer' => '<button type="button" id="country_to_data" class="btn btn-success">Add</button>
                     <button type="button" id="close-btn-flight" class="btn btn-default" data-dismiss="modal">Close</button>',
]);

Pjax::begin(['id' => 'country_to_container']);

echo Select2::widget([
    'name'          => 'country',
    'value'         => 'Bangladesh',
    'id'            => 'info_modal',
    'pluginOptions' => [
        'placeholder'        => 'Select country',
        'minimumInputLength' => 3,
        'ajax'               => [
            'url'      => '',
            'dataType' => 'json',
            'method'   => 'GET',
            'data'     => new JsExpression('function(params) { return { name:params.term }; }'),
            'processResults'=> new JsExpression('function (data) {             
                     return {
                        results: $.map(data.response, function(obj) {
                            return { id: obj.lat, text: obj.name };
                        })
                    };
                }')
        ]
    ],
]);
Pjax::end();
Modal::end();
?>




Here is tinymce.plugin.js used as external plugin

tinymce.PluginManager.add('infoto', function(editor, url) {
    // Add a button that opens a window
    editor.ui.registry.addButton('infoto', {
        text: 'Add Info',
        onAction: function () {
            // Open window
            $('#info_modal').modal();
        }
    });
});

Add created by and created_at before save in yii2

You can add this code to save created_at, updated_at, created_by in model class

public function beforeSave($insert)
{
    if.($this->isNewRecord) {
        $this->created_by = Yii::$app->user->id;
        $this->code = Utils::uniqueCode(32);
    } else {
        $this->updated_by = Yii::$app->user->id;
        $this->updated_at = date('Y-m-d H:i:s');
    }

    return parent::beforeSave($insert);
}

Create slug in yii2 with sluggable behavior

Add a sluggable behavior in model:

public function behaviors()
{
    $post = Yii::$app->request->post();
    if .(!empty($post['BlogPost']['slug'])){
        return [
            [
                'class' => SluggableBehavior::class,
                'attribute' => 'slug',
                 'slugAttribute' => 'slug',
            ],
        ];
    }
    return [
        [
            'class' => SluggableBehavior::class,
            'attribute' => 'title'
        ],
    ];
}

Create relational column sortable in yii2

Suppose you have category_id field and you wish to make category name sortable.

GridView::widget([
         'dataProvider' => $dataProvider,
         'columns' => [
             ['class' => 'kartik\grid\SerialColumn'],
             'title',           
             [
                 'attribute' => 'category.name',
                 'label' => 'Category'
             ]            
             ],
         ]       
     ]);

In model:

public function getCategory()
{
    return $this->hasOne(BlogCategory::class, ['id' => 'category_id']);
}

Show data and image in yii2 view with DetailView widget

Here is an example of view data and image data

<?= DetailView::widget([
    'model' => $model,
    'attributes' => [
        'title',
        'sub_title',
        [
            'attribute' => 'img_src',
            'format' => 'html',
            'label' => 'Image',
            'value' => function ($data) {
                return Html::img($data['img_src']);
            },
        ],
        'button_text',
        'link',
    ],
]) ?>