How to Automatically Deploy a Git Repo from Bitbucket

This article shows you how to automatically deploy your app from a git repo hosted at Bitbucket. That is, whenever you push your master branch to Bitbucket, Bitbucket will POST to a URL on your server, which will then pull and deploy the repo.

The code in this article is based on this tutorial.

Configuration

  1. In ServerPilot, create an app. We’ll use APPNAME to refer to the name you chose for this app.
  2. SSH into the server as your app’s system user; we use the serverpilot user in this tutorial.
  3. Run ssh-keygen to generate an SSH key. Don’t assign it a password.
  4. Add the public key to your Bitbucket account’s SSH keys.
  5. cd ~/apps/APPNAME
  6. git clone --mirror git@bitbucket.org:USERNAME/REPONAME.git repo, which checks out the repo to a directory called repo.
  7. Do an initial deployment from the command line by running:
    cd repo
    GIT_WORK_TREE=/srv/users/serverpilot/apps/APPNAME/public git checkout -f master
  8. Create the file ~/apps/APPNAME/public/bitbucket-deploy.php with the following contents (be sure to replace APPNAME with the name of your app):
    <?php
    $repo_dir = '/srv/users/serverpilot/apps/APPNAME/repo';
    $web_root_dir = '/srv/users/serverpilot/apps/APPNAME/public';
    
    // Full path to git binary is required if git is not in your PHP user's path. Otherwise just use 'git'.
    $git_bin_path = 'git';
    
    $update = false;
    
    // Parse data from Bitbucket hook payload
    $payload = json_decode($_POST['payload']);
    
    if (empty($payload->commits)){
      // When merging and pushing to bitbucket, the commits array will be empty.
      // In this case there is no way to know what branch was pushed to, so we will do an update.
      $update = true;
    } else {
      foreach ($payload->commits as $commit) {
        $branch = $commit->branch;
        if ($branch === 'master' || isset($commit->branches) && in_array('master', $commit->branches)) {
          $update = true;
          break;
        }
      }
    }
    
    if ($update) {
      // Do a git checkout to the web root
      exec('cd ' . $repo_dir . ' && ' . $git_bin_path  . ' fetch');
      exec('cd ' . $repo_dir . ' && GIT_WORK_TREE=' . $web_root_dir . ' ' . $git_bin_path  . ' checkout -f');
    
      // Log the deployment
      $commit_hash = shell_exec('cd ' . $repo_dir . ' && ' . $git_bin_path  . ' rev-parse --short HEAD');
      file_put_contents('deploy.log', date('m/d/Y h:i:s a') . " Deployed branch: " .  $branch . " Commit: " . $commit_hash . "\n", FILE_APPEND);
    }
    ?>
    
  9. Add a POST hook for the repo in Bitbucket with the URLhttp://YOURDOMAIN/bitbucket-deploy.php.
  10. Make changes, commit them to the “master” branch, and push.
  11. The files were now deployed to ~/apps/APPNAME/public as intended.
  12. For additional security, change the name of bitbucket-deploy.php to something containing random characters, such as bitbucket-deploy-23d98th98y.php. If you do that, don’t forget to update the URL you configured in Bitbucket.

For debugging, the script in that blog post creates a log file at~/apps/APPNAME/public/deploy.log. You can also check your app’s nginx logs if you aren’t sure Bitbucket made the request.

Source: https://serverpilot.io/community/articles/how-to-automatically-deploy-a-git-repo-from-bitbucket.html

Customize Bitbucket server port with 80

First of all, navigate to Bitbucket installation directory.

e.g.:

C:\Atlassian

For modifying the default server port to 80 with exists apache server, navigate to ApplicationData directory.

e.g.:

C:\Atlassian\ApplicationData\Bitbucket\shared

(This tutorial was created with Bitbucket v4.9.1)

Stop your bitbucket server for better performance.

Open server.xml file and go to line 71 or search for :

<Connector port="7990"

And add new values before end the tag.

scheme="http"
proxyName="git"
proxyPort="80"
/>

So the whole section will be looks like,

<Connector port="7990" protocol="HTTP/1.1"
connectionTimeout="20000"
useBodyEncodingForURI="true"
redirectPort="8443"
compression="on"
compressableMimeType="text/html,text/xml,text/plain,text/css,application/json,application/javascript,application/x-javascript"
scheme="http"
proxyName="MY_DOMAIN_NAME_HERE"
proxyPort="80"
/>

Save the file and navigate to your apache virtual host configuration file and create or add a new virtual host.

e.g.:


<VirtualHost MY_DOMAIN_NAME_HERE:80>
ProxyPreserveHost On

ProxyPass / http://MY_DOMAIN_NAME_HERE:7990/
ProxyPassReverse / http://MY_DOMAIN_NAME_HERE:7990/

ServerName MY_DOMAIN_NAME_HERE

</VirtualHost>

Save the file and restart apache and start the bitbucket server. If everything works fine, bitbucket server will be run with Apache server and http default port 80 simultaneously without any problem.

Create Service on Laravel 5

First of all, create a new folder at app directory. You can name it Services as well.

Now visit your newly created Services directory and create a new PHP file with contains class and functions. (I am going to demonstrate with creating a random string generator.)


<?php
namespace App\Services;

class randString{

public static function randomString( $type = 'nozero', $length = 6 )
{

switch ( $type ) {
case 'allstr':
$pool = '0123456789abcdefghijklmnopqrstuvwxyz';
break;
case 'alpha':
$pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'hexdec':
$pool = '0123456789abcdef';
break;
case 'numeric':
$pool = '0123456789';
break;
case 'nozero':
$pool = '123456789';
break;
case 'distinct':
$pool = '2345679acdefhjklmnprstuvwxyz';
break;
default:
$pool = (string) $type;
break;
}

$crypto_rand_secure = function ( $min, $max ) {
$range = $max - $min;
if ( $range < 0 ) return $min; // not so random...
$log = log( $range, 2 );
$bytes = (int) ( $log / 8 ) + 1; // length in bytes
$bits = (int) $log + 1; // length in bits
$filter = (int) ( 1 << $bits ) - 1; // set all lower bits to 1
do {
$rnd = hexdec( bin2hex( openssl_random_pseudo_bytes( $bytes ) ) );
$rnd = $rnd & $filter; // discard irrelevant bits
} while ( $rnd >= $range );
return $min + $rnd;
};

$token = "";
$max = strlen( $pool );
for ( $i = 0; $i < $length; $i++ ) {
$token .= $pool[$crypto_rand_secure( 0, $max )];
}
return $token;
}

}

Now you can save the file with your desired name as you like (e.g.: randString.php). Now explaining the code subjects:

The first namespace App\Services; section is including our Services folder where the files available for use.

App is the directory name (Root) and then Services is the sub directory where your newly created PHP file is available.

class randString{} is the class name which i have created for storing my functions there… You can name your class name whatever you want.

After that i have added one function which random string generator codes. You can store anything you wants.

You are all set to go next step:

Visit your config/app.php file and add a new line to your ‘aliases’ => []

'randString' => 'App\Services\randString',

Here the “randString” is my call name which i am going to use for call the functions. and then after the associative array locates the PHP file location where it is stored. If you are saved your file to another folder name or other file name, you have to change the information. Without changing the information’s, the service will not work. Save the file now.

Now we are finished the major tasks. I am going to show how this are going to work now…


Route::get('/str', function () {

echo randString::randomString('allstr', 6); // 6 is the amount of character will be output

});

I have showed the example by adding into routes.php file. You can also add this to your Controller files also.

After save the routes.php file, visit your domain name and then the string URL location. e.g.: localhost/str . You will get output like:

u9zuf6

Increase Low memory

How to increase the memory space in my system?

Bitnami stacks for web applications install servers like Apache, MySQL, PostgreSQL and others. Some of them requires more than 1Gb of memory to work properly. If you have less than 1Gb of total memory you can do the following to increase it.

– If you are using a Virtual Machine or a Cloud Image, it is possible to increase the RAM of your system

– If you do not have swap space in your system, you can create a swap file for increasing the system memory space

What is swap?

Linux swaps allow a system to harness more memory than was originally physically available (RAM). Swap space is the area on hard disk that holds memory pages that are inactive, freeing up the physical memory for other uses.

It is recommended to have swap space in your system. You can check your current swap space running the command “free”. For example:

$ free -m
             total       used       free     shared    buffers     cached
Mem:           491        144        346          0          2         25
-/+ buffers/cache:        117        374
Swap:          975         81        894

In the example above, the machine has 419MB of RAM and 975MB for swap.

How do I create a swap file?

It’s highly recommended that the swap space should be equal or bigger than the amount of physical memory (RAM). If you have less than 1Gb of memory,  it is recommended to create at least 1GB for swap. This section will cover how to create 1GB file for swap in your Linux system.

Before creating the swap space, you can identify a partition onto which you can safely put the swap file. If you have an ephimeral partition, that is ideal for this.

$ sudo dd if=/dev/zero of=/mnt/swap.0 bs=1024 count=1048576
$ sudo mkswap /mnt/swap.0
$ sudo su 

Change to root user in the machine and run the following commands:

root# echo "/mnt/swap.0 swap swap defaults 0 0" >> /etc/fstab
root# swapon /mnt/swap.0

You can check if swap space was properly enabled with the “free” command or the command below:

$ sudo swapon -s

Source: Bitnami

Choosing an Internal Top Level Domain Name

RFC 2606 lists the following TLDs reserved for private testing:

  • .test
  • .example
  • .invalid
  • .localhost

As you can see from the names, this was created for testing and not for production.

I strongly advise you to reserve your own domain name on the Internet, even if you are not planning on using it in the near future. At the least it will ensure that no conflicts will occur with some other business on the Internet with a similar name.

Source: Ashraf Al-Dabbas

Laravel Directory Permission

If you encounter directory permission for your laravel based projects. You can try to solve the permission issues by following this tips.

I have tested with Laravel Framework version 5.2.41 . but i hope this tutorial will works with other versions also.

If you have Customized apache/ nginx server or using DigitalOcean or Amazon Web Services, that might be work fine.

First of all after uploading your laravel codes into web server, change the directory permissions for storage & storage/logs

sudo chmod 755 -R YOUR_ROOT_FOLDER
chmod -R o+w YOUR_ROOT_FOLDER/storage 

Now reload your website and verify if the problem fixed. If nothing happens, or shows 500 error then,

# Group Writable (Group, User Writable)
$ sudo chmod -R gu+w YOUR_ROOT_FOLDER

World-writable (Group, User, Other Writable)
$ sudo chmod -R guo+w YOUR_ROOT_FOLDER

Root folder could be, /var/www or /www or project/ or laravel-blog/

Although, this is the destination where your all the laravel codes/ project available.

Hope your problem will be fixed.

RubyGems আপডেট করার পদ্ধতি

RubyGems হচ্ছে Ruby programming language এর প্যাকেজ ম্যানেজমেন্ট ফ্রেমওয়ার্ক।

RubyGems ব্যবহার করার মাধ্যমে রুবি প্রোগ্রামিং ল্যাংগুয়্যাজের প্যাকেজ এর ব্যবহারকে এক্সটেন্ড করা যায়।

উক্ত পদ্ধতিটি উইন্ডোজ, ম্যাক ও লিন্যাক্স ভিত্তিক অপারেটিং সিস্টেম এর জন্য কার্যকরি।

(কমান্ড লাইন ইন্টারফেস বা টার্মিনাল দিয়ে কাজ করতে হবে। লিন্যাক্স এর ক্ষেত্রে Root অথবা Sudo ব্যবহার করে এডমিন হিসেবে কাজ করতে পারেন।)

ধাপ ১ঃ


gem update --system

or

sudo gem update --system (Linux or MAC)

যদি আপনার সফটওয়্যার এর ভার্সন পূরাতন হয় অথবা রুবিজেমস ইনস্টল না করা থাকে তাহলে ইনস্টল করে নিতে কমান্ড লিখুনঃ


gem install rubygems-update

or

sudo gem install rubygems-update

অতপর রুবিজেমস আপডেট ইনস্টল হয়ে গেলে আরেকটি কমান্ড লিখুনঃ

update_rubygems

আপনার কার্যক্রম সফল হয়ে গেলে পূনরায় আপনার অপারেটিং সিস্টেম এর রুবিজেমস আপডেট করুনঃ


gem update --system

or

sudo gem update --system (Linux or MAC)