ichadhr
2/5/2017 - 7:00 PM

Nginx, PHP, MariaDB, Redis, nodejs, Ruby

Nginx, PHP, MariaDB, Redis, nodejs, Ruby

Install MariaDB and secure installation

Add repo:

# MariaDB 10.1 repository list - created 2017-02-05 01:48 UTC
# http://downloads.mariadb.org/mariadb/repositories/
deb [arch=amd64,i386] http://kartolo.sby.datautama.net.id/mariadb/repo/10.1/debian jessie main
deb-src http://kartolo.sby.datautama.net.id/mariadb/repo/10.1/debian jessie main
sudo apt-get install software-properties-common
sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 0xcbcb082a1bb943db
$ sudo apt-get install mariadb-server mariadb-client

Secure MariaDB installation:

$ mysql_secure_installation

Install Nginx and setup configuration

Add nginx repo:

# nginx repo
deb http://nginx.org/packages/debian/ jessie nginx
deb-src http://nginx.org/packages/debian/ jessie nginx
$ sudo apt-get install nginx

Open config file:

$ sudo vim /etc/nginx/nginx.conf

Setup the worker_processes based on number of CPU, use lscpu to see available core CPU.

worker_processes 2;

user  www-data;
worker_processes  2;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

Edit default nginx configuration:

$ sudo vim /etc/nginx/conf.d/default.conf
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;

    root /srv/www/html;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }

    # pass the PHP scripts to FastCGI server listening on unix socket
    location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        if (!-f $document_root$fastcgi_script_name) {
            return 404;
        }

        include fastcgi_params;
    #
    #   # With php5-cgi alone:
    #   fastcgi_pass 127.0.0.1:9000;
    #   # With php5-fpm:
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
        #include fastcgi_params;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }
}

Create server block (vhost) for apps.

cd /etc/nginx
sudo rm sites-enabled/default
sudo cp sites-available/default sites-available/mtl3.dev
sudo ln -s /etc/nginx/sites-available/mtl3.dev /etc/nginx/sites-enabled/mtl3.dev

Edit my-default sites-available

sudo vim /etc/nginx/sites-available/mtl3.dev
server {
        listen   80;
        listen [::]:80;
        server_name mtl3.dev www.mtl3.dev;

        root   /srv/www/site/mtl3.dev;
        index  index.php index.html;
        error_log /var/log/nginx/error.log;

        # set expiration of assets to MAX for caching
        location ~* .(ico|css|js|gif|jpe?g|png)(\?[0-9]+)?$ {
                expires max;
                log_not_found off;
        }

        # main codeigniter rewrite rule
        location / {
                try_files $uri $uri/ /index.php;
        }

        # php parsing
        location ~ \.php$ {
            root            /srv/www/site/mtl3.dev;
            try_files       $uri =404;
            fastcgi_pass    unix:/var/run/php5-fpm.sock;
            fastcgi_index   index.php;
            fastcgi_param   SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include         fastcgi_params;

            # fastcgi_buffer_size 128k;
            # fastcgi_buffers 256 4k;
            # fastcgi_busy_buffers_size 256k;
            # fastcgi_temp_file_write_size 256k;
        }

}

Test nginx configuration:

sudo nginx -t

Install PHP5 and Module

sudo apt-get install php5 php5-fpm php5-mysqlnd php5-redis php5-mcrypt php5-apcu php5-json re2c php5-mbstring

If necessary setup php.ini to prevent an attacker excuting http://example.com/foo.jpg/nonexistent.php:

sudo vim /etc/php5/fpm/php.ini

Change CGI fix path cgi.fix_pathinfo=0

sudo service php5-fpm restart

Install Redis server

sudo apt-get install make gcc g++ tcl8.5

Download Redis package and unpack:

mkdir -p /tmp/redis
cd /tmp/redis
wget http://download.redis.io/releases/redis-stable.tar.gz
tar xzf redis-stable.tar.gz
cd redis-stable

Proceed to with the make command:

make

Run the recommended make test:

make test

Finish up by running make install, which installs the program system-wide:

sudo make install clean

Once the program has been installed, Redis comes with a built in script that sets up Redis to run as a background daemon:

cd utils

From there, run the Ubuntu/Debian install script:

sudo ./install_server.sh

You can start and stop redis with these commands (the number depends on the port you set during the installation. 6379 is the default port setting):

sudo service redis_6379 start
sudo service redis_6379 stop

To set Redis to automatically start at boot, run:

sudo update-rc.d redis_6379 defaults

Securing Redis with binding to localhost:

sudo vim /etc/redis/6379.conf

Locate this line and make sure it is uncommented (remove the # if it exists):

bind 127.0.0.1

Additional Redis setup (skip if not necessary)

Add user redis

sudo useradd -s /bin/false -d /var/lib/redis -M redis

create Redis pid file directory

sudo mkdir /var/run/redis/ -p && sudo chown redis:redis /var/run/redis

create Redis config directory

sudo mkdir /etc/redis && sudo chown redis:redis /etc/redis -Rf

create Redis logs directory

sudo mkdir /var/log/redis/ -p && sudo chown redis:redis /var/log/redis/ -Rf

create Redis config and put it to /etc/redis/redis.conf:

sudo mkdir /etc/redis
sudo cp redis.conf /etc/redis/redis.conf
sudo chown redis:redis /etc/redis/redis.conf

Edit redis.conf. below minimum configuration example:

#start as a daemon in background
daemonize yes
#where to put pid file
pidfile /var/run/redis/redis.pid
#loglevel and path to log file
loglevel warning
logfile /var/log/redis/redis.log
#set port to listen for incoming connections, by default 6379
port 6379
#set IP on which daemon will be listening for incoming connections
bind 127.0.0.1
#where to dump database
dir /var/lib/redis

create Upstart file for Redis

sudo touch /etc/init/redis.conf

Put text below to /etc/init/redis.conf file

#!upstart
description "redis server"
start on runlevel [2345]
stop on runlevel [!2345]
respawn
respawn limit 10 5
exec sudo -u redis /usr/local/bin/redis-server /etc/redis/redis.conf

Start server:

sudo service redis start

Check Redis with ping command. Redis will response with "PONG"

redis-cli ping

Create redis-server in /etc/init.d/ (redis command line) if distributions not provide it:

#! /bin/sh
### BEGIN INIT INFO
# Provides:     redis-server
# Required-Start:   $syslog $remote_fs
# Required-Stop:    $syslog $remote_fs
# Should-Start:     $local_fs
# Should-Stop:      $local_fs
# Default-Start:    2 3 4 5
# Default-Stop:     0 1 6
# Short-Description:    redis-server - Persistent key-value db
# Description:      redis-server - Persistent key-value db
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/local/bin/redis-server
DAEMON_ARGS=/etc/redis/redis.conf
NAME=redis-server
DESC=redis-server
PIDFILE=/var/run/redis.pid

test -x $DAEMON || exit 0

set -e

case "$1" in
  start)
    echo -n "Starting $DESC: "
    touch $PIDFILE
    chown redis:redis $PIDFILE
    if start-stop-daemon --start --quiet --umask 007 --pidfile $PIDFILE --chuid redis:redis --exec $DAEMON -- $DAEMON_ARGS
    then
        echo "$NAME."
    else
        echo "failed"
    fi
    ;;
  stop)
    echo -n "Stopping $DESC: "
    if start-stop-daemon --stop --retry 10 --quiet --oknodo --pidfile $PIDFILE --exec $DAEMON
    then
        echo "$NAME."
    else
        echo "failed"
    fi
    rm -f $PIDFILE
    ;;

  restart|force-reload)
    ${0} stop
    ${0} start
    ;;

  status)
    echo -n "$DESC is "
    if start-stop-daemon --stop --quiet --signal 0 --name ${NAME} --pidfile ${PIDFILE}
    then
        echo "running"
    else
        echo "not running"
        exit 1
    fi
    ;;

  *)
    echo "Usage: /etc/init.d/$NAME {start|stop|restart|force-reload}" >&2
    exit 1
    ;;
esac

exit 0

Setting redis background saving is failing with a fork()

echo 1 > /proc/sys/vm/overcommit_memory

Install nodejs

As root user do: more info

curl -sL https://deb.nodesource.com/setup_6.x | bash -
apt-get install -y nodejs

Optional install npm global without sudo:

wget https://raw.githubusercontent.com/glenpike/npm-g_nosudo/master/npm-g-nosudo.sh
bash npm-g-nosudo.sh

Additional add ruby

Install ruby using rbenv

Visit https://github.com/rbenv/rbenv Install dependencies first:

sudo apt-get install -y libssl-dev libreadline-dev zlib1g-dev

Clone the repo:

git clone https://github.com/rbenv/rbenv.git ~/.rbenv

Add PATH to system:

echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(rbenv init -)"' >> ~/.zshrc

Install rbenv plugins install:

git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build

Get list available ruby

rbenv install -l

Setup global ruby

rbenv global