Thursday 26 February 2015

Configure sails.js / express.js to run with nginx

Pretty simple:

server {
    listen       80;
rewrite ^(.*)$ $scheme://$1;

server {
    listen       80;
    root   /var/www/example;
    index  index.php;
    access_log   /var/log/nginx/example.access.log main;

    #deny access to protected directories
    # prevent nginx from serving dotfiles (.htaccess, .svn, .git, etc.)
    location ~ /\. { deny all; access_log off; log_not_found off; }

    #location = /favicon.ico { log_not_found off; access_log off; }

    #avoid processing of calls to unexisting static files by yii
    location ~ (js|css|png|jpg|gif|ico|pdf|zip|rar)$ { try_files $uri =404;}
location ~* \.(ico|css|js|gif|jpe?g|png|swf)$ {expires 30d; access_log off; }
   location / {

#auth_basic "Access";
        #auth_basic_user_file /etc/nginx/.htpasswd;

      proxy_pass http://localhost:1337;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection 'upgrade';
      proxy_set_header Host $host;
      proxy_cache_bypass $http_upgrade;

PM2 - production process manager for Node.js

original :

PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks.
PM2 is constantly assailed by more than 300 tests.
Compatible with io.js and Node.js. Compatible with CoffeeScript. Works on Linux (stable) & MacOSx (stable) & Windows (bĂȘta).
NPM versionGitterBuild StatusInline docs

Install PM2

$ npm install pm2 -g
npm is a builtin CLI when you install Node.js - Installing Node.js or io.js with NVM

Start an application

$ pm2 start app.js

Main features

Process management

Once apps are started you can list and manage them easily:
Process listing
Listing all running processes:
$ pm2 list
Managing your processes is straightforward:
$ pm2 stop     <app_name|id|all>
$ pm2 restart  <app_name|id|all>
$ pm2 delete   <app_name|id|all>
To have more details on a specific process:
$ pm2 describe 0


Monitoring all processes launched:
$ pm2 monit

Log facilities

Displaying logs of a specified process or all processes, in real time:
$ pm2 logs
$ pm2 logs big-api
$ pm2 flush          # Clear all the logs

Load balancing / 0s reload downtime

When an app is started with the -i option, the cluster mode is enabled.
Warning: It's still a beta feature. If you want to use the embed cluster module or reload with 0s downtime, we recommend the use of node#0.12.0+ node#0.11.16+ or io.js#1.0.2+. We do not support node#0.10.* cluster module anymore!
With the cluster mode, PM2 enables load balancing between each worker. Each HTTP/TCP/UDP request will be forwarded to one specific process at a time.
$ pm2 start app.js -i max  # Enable load-balancer and cluster features

$ pm2 reload all           # Reload all apps in 0s manner

Startup script generation

PM2 can generate and configure a startup script to keep PM2 and your processes alive at every server restart.
$ pm2 startup
# auto-detect platform
$ pm2 startup [platform]
# render startup-script for a specific platform, the [platform] could be one of:
#   ubuntu|centos|redhat|gentoo|systemd|darwin|amazon
For Centos worked example 
#sudo env PATH=$PATH:/usr/local/bin pm2 startup centos -u root

To save a process list just do:
$ pm2 save

Disabling SELinux

Disabling SELinux

Before all -

~]$ setenforce Permissive

sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
To disable SELinux, configure SELINUX=disabled in /etc/selinux/config:

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#       permissive - SELinux prints warnings instead of enforcing.
#       disabled - No SELinux policy is loaded.
# SELINUXTYPE= can take one of these two values:
#       targeted - Targeted processes are protected,
#       mls - Multi Level Security protection.

Reboot your system. After reboot, confirm that the getenforce command returns Disabled:

~]$ getenforce

Saturday 21 February 2015

git : Subdirectory Checkouts with git sparse-checkout

Original post:

Subdirectory Checkouts with git sparse-checkout

By  in git
If there is one thing I miss about SVN having switched to git (and trust me, it’s the only thing), it is the ability to checkout only a sub-tree of a repository. As of version 1.7, you can check out just a sub-tree in git as well! Now not only does git support checking out sub-directories, it does it better than subversion!

New Repository

There is a bit of a catch-22 when doing a sub-tree checkout for a new repository. In order to only checkout a sub-tree, you’ll need to have the core.sparsecheckout option set to true. Of course, you need to have a git repository before you can enable sparse-checkout. So, rather than doing a git clone, you’ll need to start with git init.
  1. Create and initialize your new repository:
    mkdir <repo> && cd <repo>
    git init
    git remote add –f <name> <url>
  2. Enable sparse-checkout:
    git config core.sparsecheckout true
  3. Configure sparse-checkout by listing your desired sub-trees in .git/info/sparse-checkout:
    echo some/dir/ >> .git/info/sparse-checkout
    echo another/sub/tree >> .git/info/sparse-checkout
  4. Checkout from the remote:
    git pull <remote> <branch>

mkdir test_site_root && cd test_site_root
git init
git remote add origin https://git-url/test_site_root.git
git config core.sparsecheckout true
echo test_site_node >> .git/info/sparse-checkout
git pull origin master

Result: will pulled  test_site_root/test_site_node folder from git
Existing Repository
If you already have a repository, simply enable and configure sparse-checkout as above and do git read-tree.
  1. Enable sparse-checkout:
    git config core.sparsecheckout true
  2. Configure sparse-checkout by listing your desired sub-trees in .git/info/sparse-checkout:
    echo some/dir/ >> .git/info/sparse-checkout
    echo another/sub/tree >> .git/info/sparse-checkout
  3. Update your working tree:
    git read-tree -mu HEAD

Modifying sparse-checkout sub-trees

If you later decide to change which directories you would like checked out, simply edit the sparse-checkout file and run git read-tree again as above.
Be sure to read the documentation on read-tree/sparse-checkout. The sparse-tree file accepts file patterns similar to .gitignore. It also accepts negations—enabling you to specify certain directories or files to not checkout.
Now there isn’t anything that svn does better than git!

Install nginx on Centos 7

Install nginx on Centos 7
    #Disable SELinux !!!!!:
    # install nging
    # set firewall
    # start
    # Start on system start
    # move folder www to vars

 yum install nginx -y
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --reload
service nginx start
sudo chkconfig --levels 235 nginx on

 if /var/www not exists -

    mkdir /var/www
    chown -R nginx:nginx /var/www
    mv -v /usr/share/nginx/html/ /var/www
    chmod -R 0755 /var/www

#edit /etc/nginx/nginx.conf to new www path
# take config example :
service nginx restart

How To Set Up HTTP Authentication With Nginx

printf "USER:$(openssl passwd -crypt PASSWORD)\n" >> .htpasswd
Replace USER and PASSWORD for your user and password 

Your nginx configuration file for the website should be under /etc/nginx/sites-available/. Add the two entries below under for the domain path that you want to secure.
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;
The second line is the location of the htpasswd file for your website.

If you familiar with paranoia, and not disabled SELinux

Set SELinux permissions !!!!
I experienced the same problem and it was due to SELinux.
To check if SELinux is running:
# getenforce
To disable SELinux until next reboot:
# setenforce Permissive
Restart Nginx and see if the problem persists. If you would like to permanently alter the settings you can edit /etc/sysconfig/selinux
If SELinux is your problem you can run the following to allow nginx to serve your www directory (make sure you turn SELinux back on before testing this. i.e, # setenforce Enforcing)
# chcon -Rt httpd_sys_content_t /path/to/www
If you're still having issues take a look at the boolean flags in getsebool -a, in particular you may need to turn on httpd_can_network_connect for network access
# setsebool -P httpd_can_network_connect on
For me it was enough to allow http to serve my www directory.
Set writable directories :  
chown nginx -R /var/www..../web/runtime
chown nginx -R /var/www/..../www/assets

How To Install Linux, nginx, MySQL, PHP (LEMP) stack on CentOS

Original post:

How To Install Linux, nginx, MySQL, PHP (LEMP) stack on CentOS 6

About Lemp

LEMP stack is a group of open source software to get web servers up and running. The acronym stands for Linux, nginx (pronounced Engine x), MySQL, and PHP. Since the server is already running CentOS, the linux part is taken care of. Here is how to install the rest.

Step One—Install the Required Repositories

We will be installing all of the required software with Yum. However, because nginx is not available straight from CentOS, we'll need to install the epel repository.
sudo yum install epel-release

Step Two—Install MySQL

The next step is to begin installing the server software on the virtual private server, starting with MySQL and dependancies.
 sudo yum install mysql-server
Once the download is complete, restart MySQL:
sudo /etc/init.d/mysqld restart
You can do some configuration of MySQL with this command:
sudo /usr/bin/mysql_secure_installation
The prompt will ask you for your current root password.
Since you just installed MySQL, you most likely won’t have one, so leave it blank by pressing enter.
Enter current password for root (enter for none): 
OK, successfully used password, moving on...
Then the prompt will ask you if you want to set a root password. Go ahead and choose Y and follow the instructions.
CentOS automates the process of setting up MySQL, asking you a series of yes or no questions.
It’s easiest just to say Yes to all the options. At the end, MySQL will reload and implement the changes.
By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y                                            
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y
... Success!

By default, MySQL comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MySQL
installation should now be secure.

Thanks for using MySQL!

Step Three—Install nginx

As with MySQL, we will install nginx on our virtual private server using yum:
sudo yum install nginx
nginx does not start on its own. To get nginx running, type:
sudo /etc/init.d/nginx start
You can confirm that nginx has installed on your virtual private server by directing your browser to your IP address.
You can run the following command to reveal your server’s IP address.
ifconfig eth0 | grep inet | awk '{ print $2 }'


Step Four—Install PHP

The php-fpm package is located within the REMI repository, which, at this point, is disabled. The first thing we need to do is enable the REMI repository and install php and php-fpm:
sudo yum install php-fpm php-mysql

Step Five—Configure php

We need to make one small change in the php configuration. Open up php.ini:
 sudo vi /etc/php.ini
Find the line, cgi.fix_pathinfo=1, and change the 1 to 0.
If this number is kept as a 1, the php interpreter will do its best to process the file that is as near to the requested file as possible. This is a possible security risk. If this number is set to 0, conversely, the interpreter will only process the exact file path—a much safer alternative. Save and Exit.

Step Six—Configure nginx

Open up the default nginx config file:
sudo vi /etc/nginx/nginx.conf
Raise the number of worker processes to 4 then save and exit that file.
Now we should configure the nginx virtual hosts.
In order to make the default nginx file more concise, the virtual host details are in a different location.
sudo vi /etc/nginx/conf.d/default.conf
The configuration should include the changes below (the details of the changes are under the config information):
# The default server
server {
    listen       80;

    location / {
        root   /usr/share/nginx/html;
        index index.php  index.html index.htm;

    error_page  404              /404.html;
    location = /404.html {
        root   /usr/share/nginx/html;

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;

    # pass the PHP scripts to FastCGI server listening on
    location ~ \.php$ {
        root           /usr/share/nginx/html;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
        include        fastcgi_params;

Here are the details of the changes:
  • Add index.php within the index line.
  • Change the server_name to your domain name or IP address (replace the in the configuration)
  • Change the root to /usr/share/nginx/html;
  • Uncomment the section beginning with "location ~ \.php$ {",
  • Change the root to access the actual document root, /usr/share/nginx/html;
  • Change the fastcgi_param line to help the PHP interpreter find the PHP script that we stored in the document root home.
Save and Exit
Open up the php-fpm configuration:
sudo vi /etc/php-fpm.d/www.conf
Replace the apache in the user and group with nginx:
; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
; will be used.
; RPM: apache Choosed to be able to access some dir as httpd
user = nginx
; RPM: Keep a group allowed to write in log dir.
group = nginx
Finish by restarting php-fpm.
sudo service php-fpm restart

Step Seven—RESULTS: Create a php info page

Although LEMP is installed, we can still take a look and see the components online by creating a quick php info page
To set this up, first create a new file:
sudo vi /usr/share/nginx/html/info.php
Add in the following line:
Then Save and Exit.
Restart nginx so that all of the changes take effect:
sudo service nginx restart
Finish up by visiting your php info page (make sure you replace the example ip address with your correct one):
It should look similar to this.

Step Eight—Set Up Autostart

You are almost done. The last step is to set all of the newly installed programs to automatically begin when the VPS boots.
sudo chkconfig --levels 235 mysqld on
sudo chkconfig --levels 235 mariadb on
sudo chkconfig --levels 235 nginx on
sudo chkconfig --levels 235 php-fpm on

Install YII on Centos

Yii on Centos 6 Linux (64 bit) Installation

Now install PHP and Http packages

[root@yii ~]# yum -y install unzip php-fpm php-mysql

Modify using a text editor, locate date.timezone in the file /etc/php.ini for the timezone that is appropriate for your server. I.e. date.timezone = America/New_York

sed -i 's/;date.timezone =/date.timezone = America\/New_York/g' /etc/php.ini


[root@yii /]# sudo nano /etc/php.ini

Setup php-fpm

sed -i 's/user = apache/user = nginx/g' /etc/php-fpm.d/www.conf
sed -i 's/group = apache/group = nginx/g' /etc/php-fpm.d/www.conf


Open up the php-fpm configuration:
[root@yii ~]# sudo nano /etc/php-fpm.d/www.conf

service php-fpm restart

Fresh install YII:

Check for the latest release of Yii under 

[root@yii ~]# cd /var/www
[root@yii html]# wget

Unzip and change the mode to 755 for all files in the extracted directory

[root@yii www]# unzip -d /var/www

[root@yii www]# chown -R nginx:nginx /var/www/yii-1.1.10.r3566
[root@yii www]#  chmod -R 755 /var/www/yii-1.1.10.r3566

chown nginx -R /var/www/DOMAIN/web/runtime chown nginx -R /var/www/DOMAIN/www/assets 

Create your test application 

[root@yii www]# php /var/www/yii-1.1.10.r3566/framework/yiic.php webapp /var/www/html/test 

Using a browser go to your newly created Yii web application "test"



Attention for Users used