Nginx (pronounced “engine x”) is a free, open-source, high-performance HTTP server. Nginx is known for its stability, rich feature set, simple configuration, and low resource consumption. This tutorial shows how you can install Nginx on an Ubuntu 16.04 server with PHP 7 support (through PHP-FPM) and MySQL 5.7 support (LEMP = Linux + nginx (pronounced “engine x”) + MySQL + PHP).


1 Preliminary Note

In this tutorial, I use the hostname with the IP address These settings might differ for you, so you have to replace them where appropriate.

I’m running all the steps in this tutorial with root privileges, so make sure you’re logged in as root:

sudo -s


2 Installing MySQL 5.7

In order to install MySQL, we run:

apt-get -y install mysql-server mysql-client

You will be asked to provide a password for the MySQL root user – this password is valid for the user [email protected] as well as [email protected], so we don’t have to specify a MySQL root password manually later on:

New password for the MySQL “root” user: <– yourrootsqlpassword
Repeat password for the MySQL “root” user: <– yourrootsqlpassword

To secure the database server and remove  the anonymous user and test database, run the mysql_secure_installation command.


You will be asked these questions:

[email protected]:~# mysql_secure_installation

Securing the MySQL server deployment.

Enter password for user root: <– Enter the MySQL root password

VALIDATE PASSWORD PLUGIN can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD plugin?

Press y|Y for Yes, any other key for No: <– Press y if you want this function or press Enter otherwise.
Using existing password for root.
Change the password for root ? ((Press y|Y for Yes, any other key for No) : <– Press enter

… skipping.
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

Remove anonymous users? (Press y|Y for Yes, any other key for No) : <– y

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? (Press y|Y for Yes, any other key for No) : <– y

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

Remove test database and access to it? (Press y|Y for Yes, any other key for No) : <– y
– Dropping test database…

– Removing privileges on test database…

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

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : <– y

All done!

MySQL is secured now.

3 Installing Nginx

In case that you have installed Apache2 already, then remove it first with these commands & then install nginx:

service apache2 stop
update-rc.d -f apache2 remove
apt-get remove apache2

Nginx is available as a package for Ubuntu 16.04 which we can install.

apt-get -y install nginx

Start nginx afterwards:

service nginx start

Type in your web server’s IP address or hostname into a browser (e.g., and you should see the following page:

The Ubuntu Nginx default page.

The default nginx document root on Ubuntu 16.04 is /var/www/html.


4 Installing PHP 7

We can make PHP work in nginx through PHP-FPM (PHP-FPM (FastCGI Process Manager) is an alternative PHP FastCGI implementation with some additional features useful for sites of any size, especially busier sites) which we install as follows:

apt-get -y install php7.0-fpm

PHP-FPM is a daemon process (with the init script php7.0-fpm) that runs a FastCGI server on the socket /run/php/php7.0-fpm.sock.


5 Configuring nginx

The nginx configuration is in /etc/nginx/nginx.conf which we open now:

nano /etc/nginx/nginx.conf

The configuration is easy to understand (you can learn more about it here: and here:

First (this is optional) adjust the keepalive_timeout to a reasonable value:

    keepalive_timeout   2;

The virtual hosts are defined in server {} containers. The default vhost is defined in the file /etc/nginx/sites-available/default – let’s modify it as follows:

nano /etc/nginx/sites-available/default

server {
 listen 80 default_server;
 listen [::]:80 default_server;

 # SSL configuration
 # listen 443 ssl default_server;
 # listen [::]:443 ssl default_server;
 # Note: You should disable gzip for SSL traffic.
 # See:
 # Read up on ssl_ciphers to ensure a secure configuration.
 # See:
 # Self signed certs generated by the ssl-cert package
 # Don't use them in a production server!
 # include snippets/snakeoil.conf;

 root /var/www/html;

 # Add index.php to the list if you are using PHP
 index 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
 location ~ \.php$ {
 include snippets/fastcgi-php.conf;

 # With php7.0-cgi alone:
 # fastcgi_pass;
 # With php7.0-fpm:
 fastcgi_pass unix:/run/php/php7.0-fpm.sock;

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

server_name _; makes this a default catchall vhost (of course, you can as well specify a hostname here like

root /var/www/html; means that the document root is the directory /var/www/html.

The important part for PHP is the location ~ \.php$ {} stanza. Uncomment it to enable it.

Now save the file and reload nginx:

service nginx reload

Next open /etc/php/7.0/fpm/php.ini

nano /etc/php/7.0/fpm/php.ini

… and set cgi.fix_pathinfo=0:

; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI.  PHP's
; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok
; what PATH_INFO is.  For more information on PATH_INFO, see the cgi specs.  Setting
; this to 1 will cause PHP CGI to fix its paths to conform to the spec.  A setting
; of zero causes PHP to behave as before.  Default is 1.  You should fix your scripts

Reload PHP-FPM:

service php7.0-fpm reload

Now create the following PHP file in the document root /var/www/html:

nano /var/www/html/info.php


Now we call that file in a browser (e.g.

PHP Info on Ubuntu with Nginx.

As you see, PHP 7 is working, and it’s working through FPM/FastCGI, as shown in the Server API line. If you scroll further down, you will see all modules that are already enabled in PHP. MySQL is not listed there which means we don’t have MySQL support in PHP yet.


6 Getting MySQL Support In PHP 7

To get MySQL support in PHP, we can install the php7.0-mysql package. It’s a good idea to install some other PHP modules as well as you might need them for your applications. You can search for available PHP modules like this:

apt-cache search php7.0

Pick the ones you need and install them like this:

apt-get -y install php7.0-mysql php7.0-curl php7.0-gd php7.0-intl php-pear php-imagick php7.0-imap php7.0-mcrypt php-memcache  php7.0-pspell php7.0-recode php7.0-sqlite3 php7.0-tidy php7.0-xmlrpc php7.0-xsl php7.0-mbstring php-gettext

APCu is an extension for the PHP Opcache module that comes with PHP 7, it adds some compatibility features for software that supports the APC cache (e.g. WordPress cache plugins).

APCu can be installed as follows:

apt-get -y install php-apcu

Now reload PHP-FPM:

service php7.0-fpm reload

Now reload in your browser and scroll down to the modules section again. You should now find lots of new modules there, including the MySQL module:

The PHP Modules have been installed.


7 Making PHP-FPM use a TCP Connection

By default PHP-FPM is listening on the socket /var/run/php/php7.0-fpm.sock. It is also possible to make PHP-FPM use a TCP connection. To do this, open /etc/php/7.0/fpm/pool.d/www.conf

nano /etc/php/7.0/fpm/pool.d/www.conf

… and make the listen line look as follows:

;listen = /var/run/php5-fpm.sock
listen =

This will make PHP-FPM listen on port 9000 on the IP (localhost). Make sure you use a port that is not in use on your system.

Then reload PHP-FPM:

php7.0-fpm reload

Next go through your nginx configuration and all your vhosts and change the line fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; to fastcgi_pass;, e.g. like this:

nano /etc/nginx/sites-available/default

        location ~ \.php$ {
 include snippets/fastcgi-php.conf;

 # With php7.0-cgi alone:
 # With php7.0-fpm:
 # fastcgi_pass unix:/run/php/php7.0-fpm.sock;

Finally, reload nginx:

service nginx reload

That’s it. The Nginx LEMP server is installed.

 2,192 total views,  1 views today

This can be useful if you need to cd to the script location from within crontab. cd to the script location from within the script itself !

For the relative path (i.e. the direct equivalent of Windows’ 



MY_PATH="dirname \"$0\""
echo "$MY_PATH"

For the absolute, normalized path:

MY_PATH="dirname \"$0\""              # relative
MY_PATH="( cd \"$MY_PATH\" && pwd )"  # absolutized and normalized
if [ -z "$MY_PATH" ] ; then
  # error; for some reason, the path is not accessible
  # to the script (e.g. permissions re-evaled after suid)
  exit 1  # fail
echo "$MY_PATH"

 1,060 total views

Tips to Securing your PHP Application

Karthikeyan K April 4, 2012 PHP

Now a days PHP Language is very popular among developers to develop large applications like facebook etc.

So here I am going to tell how to secure your PHP applications in a simple steps

Disabling Remote URLs for File Handling Functions

File handling functions like fopen, file_get_contents, and include accept URLs as file parameters (for example:fopen(‘’, ‘r’)). Even though this enables developers to access remote resources like HTTP URLs, it poses as a huge security risk if the filename is taken from user input without proper sanitization, and opens the door for remote code execution on the server. To disable this and limit file functions to local system, use the following setting in php.ini:

allow_url_fopen = Off
Network resources will still be accessible through fsockopen or CURL functions.

Most of the following settings are also located in the PHP configuration file php.ini. Its actual path depends on your OS. You may use the search feature to locate it if you don’t know where it is already.

Register Globals

Prior to version 4.2.0, PHP used to provide input values as global variables. This feature was named register_globals, and it was responsible for many security issues in web applications because it allowed attackers to freely manipulate global variables in many situations. Fortunately it’s disabled by default from PHP 4.2.0 and on, because it’s dangerous on so many scales. Do not enable it no matter what. If some script requires it then the script is most likely insecure. If a developer requests it to be enabled, then they are very likely to be incompetent. Don’t listen to them and keep it off!

register_globals = Off
Restricting What PHP Can Read and Write

More often than not, PHP scripts only need I/O access to a certain subdirectory in the filesystem,/var/www/htdocs/files for instance. In this case, you can limit what fopen and other file access functions can read and write to by using the following directive:

open_basedir = /var/www/htdocs/files
Safe Mode

PHP has a safe mode. In this mode, access to files not owned by Apache is disabled, and access to environment variables and execution of binary programs are also disabled.

In its default state, PHP’s safe mode is too restrictive for any advanced development to be possible. However, there are several settings to relax it. The biggest problem with safe mode is that only files owned by Apache are accessible to PHP scripts. This is often impractical when many developers are working on the same project, or when you want PHP to read a file without changing its ownership. Another affected situation is when you want PHP to read files generated by other programs. To work around this, there is a setting that checks for file group instead of owner:

safe_mode = Off
safe_mode_gid = On
With safe_mode_gid enabled instead of safe_mode, PHP will be able to open files that belong to Apache’s group regardless of the owner. So if there are several developers working on the same server, add them to Apache’s group, make it their default group, and everything should be set.

Safe mode is also useful in stopping PHP from executing binaries, but sometimes you may need to let it run specific programs. In this case place these binaries (or symbolic links to them) in a directory (/var/www/binaries for instance) and use the following option:

safe_mode_exec_dir = /var/www/binaries
Finally, to allow access to certain environment variables, use the following setting, providing a comma-separated list of prefixes. Only environment variables which names begin with one of the prefixes will be accessible:

safe_mode_allowed_env_vars = PHP_
Posing Limits

It’s always a good idea to put limits on PHP’s execution time, memory usage, POST and upload data. To do this, use the following self-explanatory options:

max_execution_time = 30  ; Max script execution time
max_input_time = 60      ; Max time spent parsing input
memory_limit = 16M       ; Max memory used by one script
upload_max_filesize = 2M ; Max upload file size
post_max_size = 8M       ; Max post size
Needless to say, you may tweak the values to suit your needs.

Limit Access to Certain File Name Patterns

Many file extensions should not be accessible by end users. Take for example .inc. Some developers prefer to assign this extension to included scripts. The problem here is that this extension isn’t parsed by the PHP engine, and as a result, anyone can view the source code by requesting the file itself:

Such files may contain sensitive data like MySQL passwords. So you need to ensure that end users can not access those files. Other candidate extensions are .sql, .mysql, and .pgsql.

Another pattern to look out for is backup files. Some editors create backup versions of edited files in the same directory where the original file is located. For example, if you edit index.php, a backup called index.php~ will be created. Given that this file doesn’t end with .php, it will not be processed by the PHP engine, and its code will also be available to users by requesting

To avoid the risks mentioned above, you can use the following Apache directive:

  Order allow,deny
  Deny from all

Place it in a .htaccess file or in Apache’s configuration. Adding more file extensions should be trivial to those familiar with regular expressions.

Error Messages and Logging

By default, PHP prints error messages to the browser’s output. While this is desirable during the development process, it may reveal security information to users, like installation paths or usernames. It’s highly recommended to disable this on a production server, and send error messages to a log file instead:

display_errors = Off
log_errors = On
Hiding The Presence Of PHP

PHP reveals its presence on the server in a variety of ways: It may send an HTTP header (X-Powered-By: PHP), or append its name and version to Apache’s signature. In addition, there are easter egg URLs that return the PHP logo, one of them is:

Obviously there is no reason to let end users know about the server’s PHP version. Luckily, there is a switch in php.ini that will disable all of the above:

expose_php = Off
If you enjoyed this article, Get email updates (It’s Free)

You Might Also Like:

3 tips to secure your wordpress using .htaccess
Tips to Speed Up your PHP Website/Application
Top 10 htaccess tips and tricks to prevent your wordpress site from hackers
Top 5 tips to speed up your wordpress blog
New features in PHP 5.4 version
Built-in Web Server Environment in PHP 5.4
Codeigniter Tips and Tricks
Build Your First Facebook Application in PHP
PHP and htaccess tips and tricks
Create a Basic Shoutbox with PHP and SQL

htaccess tips & tricks
Did you like this article? Share it with your friends!

Written by Karthikeyan K

I have more than 5 years of experience in web development arena. I have designed complex back-end management systems including content management, social networking sites and communication interfaces. The projects in my workplace are based on PHP in conjunction with various other web development technologies. My strength lies in various domains like PHP, Mysql, JavaScript, AJAX, DHTML, XHTML and CSS.

Karthikeyan K Karthikeyan K
Entrepreneur, Imagineer, Web Developer, Blogger
Chennai – India
itzurkarthi [at]
Subscribe my updates via Email

Follow Us on Facebook

Recent Posts
Getting Images from Flickr, Instagram, Twitpic, Imgur & Deviantart Url using PHP & jQuery
Facebook Style Hashtag System with PHP, MYSQL & jQuery
Image Hover Effects using CSS3
Convert Textbox / Textarea to Fullscreen Editor using jQuery
Delete Records with Multiple Animations using jQuery
Facebook Style Tag Selector using jQuery & CSS3
Protect / Secure your Website Content using jQuery
Facebook Style Homepage Design with Registration Form, Login Form using CSS3
Responsive Login Form with CSS
Top 5 Fast & Powerful Web User Interfaces – CSS3, HTML5 & Javascript
Codeigniter (6)
CSS3 (62)
facebook (22)
Freebies (87)
htaccess (4)
html5 (15)
jquery (94)
Mysql (4)
PHP (44)
twitter (4)
Uncategorized (4)
Web Design (64)
wordpress (7)
Recent Comments
bibochip on Facebook Style Profile Info Tooltip using jQuery & CSS
Pradeep on Facebook Timeline Wall Script 2.0 with PHP, Mysql, jQuery
Karthikeyan K on Facebook Style Tag Selector using jQuery & CSS3
Neo on Facebook Style Tag Selector using jQuery & CSS3
eren on Facebook Timeline Wall Script 2.0 with PHP, Mysql, jQuery
Karthik KN subbiah on Facebook Timeline Wall Script 2.0 with PHP, Mysql, jQuery
Karthikeyan K on Facebook Timeline Wall Script 2.0 with PHP, Mysql, jQuery
Karthik KN subbiah on Facebook Timeline Wall Script 2.0 with PHP, Mysql, jQuery
Web design company on Facebook Style Hashtag System with PHP, MYSQL & jQuery
Sudhanshu Pandey on Protect / Secure your Website Content using jQuery
Alexa Certified Traffic Ranking for
Visit to discover Indian blogs
Recent Posts
Getting Images from Flickr, Instagram, Twitpic, Imgur & Deviantart Url using PHP & jQuery
Facebook Style Hashtag System with PHP, MYSQL & jQuery
Image Hover Effects using CSS3
Convert Textbox / Textarea to Fullscreen Editor using jQuery
Delete Records with Multiple Animations using jQuery
Facebook Style Tag Selector using jQuery & CSS3
Protect / Secure your Website Content using jQuery
Facebook Style Homepage Design with Registration Form, Login Form using CSS3
Responsive Login Form with CSS
Top 5 Fast & Powerful Web User Interfaces – CSS3, HTML5 & Javascript
Subscribe my updates via Email

actionbar amazon cloudfront apache API Button call to action Cascading Style Sheets codeigniter CSS3 Design facebook facebook application facebook wall script favicon freebies google+ htaccess HTML5 icons image gallery javascript Jquery jquery plugin Login form message box mysql new techniques php Plug-ins plugins pricing table responsive rss feed scroll div search box Signup form slider take a tour timeline tips & tricks top bar twitter Website website speed wordpress
© 2013

Get every new post delivered to your Inbox

Join other followers


Toggle Dock
Recommended for you:

Twitter like login form, search box, top panel using Jquery and CSS
Twitter like login form, search box, top panel u…
Animated Search Box with CSS3
Animated Search Box with CSS3
Responsive HTML5 Form with jQuery
Responsive HTML5 Form with jQuery
Notification Message boxes with CSS & Jquery
Notification Message boxes with CSS & Jquery

 2,441 total views

Posted in PHP

Help & Community
Sign Up Login
Help & Community
Articles & Tutorials
Try this tutorial
on an SSD cloud server.
Includes 512MB RAM, 20GB SSD Disk, and 1TB Transfer for $5/mo! Learn more.
Related Articles
How To Install and Use Memcache on Ubuntu 12.04
How To Launch Your Site on a New Ubuntu 12.04 Server with LAMP, SFTP, and DNS
How To Set Up a Minecraft Server on Linux
How To Install Apache Tomcat on Ubuntu 12.04
How To Install Git on Ubuntu 12.04
How To Create an Node.js App Using Sails.js on an Ubuntu VPS
How To Install Node.js with NVM (Node Version Manager) on a VPS
How To Host Multiple Node.js Applications On a Single VPS with nginx, forever, and crontab
How To Install an Upstream Version of Node.js on Ubuntu 12.04
How To Install And Run A Node.js App On Centos 6.4 64bit
How To Write a Linux Daemon with Node.js on a VPS

A daemon is a program that runs in background and has no controlling terminal. They are often used to provide background services. For example, a web-server or a database server can run as a daemon.

This tutorial will show you how to write a daemon with Node.js and deploy it on your VPS with Upstart.

I will focus on implementing a standard daemon. I’m using upstart just for simplicity, however you can write a System-V init script or use anything you like to start your daemon.

For this tutorial, you will need a Linux VPS (Preferably Ubuntu or CentOS), Node.js, and Upstart.

There are several ways to install Node.js. The easiest way in my opinion is to use nvm. It also allows you to manage different versions of Node.

Alternatively, you can follow one of these guides:

How To Install an Upstream Version of Node.js on Ubuntu 12.04
Installing Node.js via package manager
Upstart comes pre-installed on many Linux distros. If it’s not installed on the distro of your choice, you should be able to install it from official repositories. You can also compile it from the source-code. Refer to Upstart Getting Started page for more info.

How Daemons Work
Basically a daemon starts like a normal process. the following will occur afterwards:

It creates a copy of itself as it’s child process.
The child detaches itself from the parent process.
The child process closes its standard file descriptors (See below.)
The parent process exits.
The daemon continues its work in background.
Instead of closing the standard file descriptors, the parent process can open the null device and attach it to the child’s standard file descriptors.

The Example Daemon
For the sake of this tutorial, we’re going to create a simple HTTP daemon.

Our daemon will be able to:

Start in the background (we’re going to use a module called “daemon” for this.)
Spawn multiple workers for HTTP server.
Restart the workers on SIGHUP.
Terminate the workers on SIGTERM.
Drop workers’ privileges after the HTTP server gets started.
Initial project structure
The following is the initial project structure:

|– bin/
|   `– node-simple-http-daemon
`– lib/
    `– app.js
Let’s start by creating a package.json file:

$ npm init
Install daemon module:

$ npm –save install daemon
And here is how the package.json should look like:

  “name”: “node-simple-http-daemon”,
  “version”: “0.0.0”,
  “description”: “Simple HTTP Daemon written in Node.js”,
  “main”: “lib/app.js”,
  “scripts”: {
    “test”: “echo \”Error: no test specified\” && exit 1″,
    “start”: “node lib/app.js”
  “author”: “Fardjad Davari”,
  “license”: “MIT”,
  “dependencies”: {
    “daemon”: “~1.1.0”
Note that we added a start script, So we can start the app with npm start command later.

HTTP Server
For now, we’re going to create a simple HTTP server that starts listening on port 80 and responds with “Hello world” for every request.

Put the following in lib/app.js file:

* lib/app.js

const PORT = 80;
const ADDRESS = ‘’;

var http = require(‘http’);

var server = http.createServer(function (req, res) {
  res.writeHead(200, {‘Content-Type’: ‘text/plain’});
  res.end(‘Hello World\n’);

server.listen(PORT, ADDRESS, function () {
    console.log(‘Server running at http://%s:%d/’, ADDRESS, PORT);
    console.log(‘Press CTRL+C to exit’);
You can start the VPS by running sudo npm start.

Daemon executable
The following is the daemon executable code.

The following should be placed in bin/node-simple-http-daemon:

#!/usr/bin/env node

* bin/node-simple-http-daemon

// Everything above this line will be executed twice

var cluster = require(‘cluster’);

// Number of CPUs
var numCPUs = require(‘os’).cpus().length;

* Creates a new worker when running as cluster master.
* Runs the HTTP server otherwise.
function createWorker() {
  if (cluster.isMaster) {
    // Fork a worker if running as cluster master
    var child = cluster.fork();

    // Respawn the child process after exit
    // (ex. in case of an uncaught exception)
    child.on(‘exit’, function (code, signal) {
  } else {
    // Run the HTTP server if running as worker

* Creates the specified number of workers.
* @param  {Number} n Number of workers to create.
function createWorkers(n) {
  while (n– > 0) {

* Kills all workers with the given signal.
* Also removes all event listeners from workers before sending the signal
* to prevent respawning.
* @param  {Number} signal
function killAllWorkers(signal) {
  var uniqueID,

  for (uniqueID in cluster.workers) {
    if (cluster.workers.hasOwnProperty(uniqueID)) {
      worker = cluster.workers[uniqueID];

* Restarts the workers.
process.on(‘SIGHUP’, function () {
  createWorkers(numCPUs * 2);

* Gracefully Shuts down the workers.
process.on(‘SIGTERM’, function () {

// Create two children for each CPU
createWorkers(numCPUs * 2);
Time to start our daemon! But before that, we should modify our app.js to
handle SIGTERM.

Add the following to the end of the app.js file:

process.on(‘SIGTERM’, function () {
  if (server === undefined) return;
  server.close(function () {
    // Disconnect from cluster master
    process.disconnect && process.disconnect();
Make the daemon script executable:

$ chmod +x bin/node-simple-http-daemon
And run it (Make sure nothing else is running on port 80):

$ sudo bin/node-simple-http-daemon
Now, your daemon and it’s workers should be running in background. You can
confirm that by sending an HTTP GET request via cURL:

$ curl
Before moving to the next step, let’s take a look at the process IDs:

$ ps -axf | grep [n]ode-simple-http-daemon | \
  awk ‘{ print “pid:”$2”, parent-pid:”$3 }’
Sample output:

pid:33811, parent-pid:1
pid:33853, parent-pid:33811
pid:33856, parent-pid:33811
pid:33857, parent-pid:33811
pid:33858, parent-pid:33811
pid:33859, parent-pid:33811
pid:33860, parent-pid:33811
pid:33861, parent-pid:33811
pid:33862, parent-pid:33811
Note that the daemon is the process with parent-pid of 1.

Try restarting the workers by sending SIGHUP to the daemon:

$ kill -HUP 33811 # (replace 33811 with the daemon PID)
Now if you list the PIDs again, you should be able to see new worker processes with new PIDs. Amazing, isn’t it?

To stop the daemon, just run:

$ kill -TERM 33811 # (replace 33811 with the daemon PID)
Dropping privileges
We’re almost done. We only need to make workers drop their privileges after the VPS gets started.

Modify server.listen() callback in app.js so it reads:

server.listen(PORT, ADDRESS, function () {
    console.log(‘Server running at http://%s:%d/’, ADDRESS, PORT);
    console.log(‘Press CTRL+C to exit’);

    // Check if we are running as root
    if (process.getgid() === 0) {
And that’s it for the daemon part.

Now you can install it system-wide:

$ sudo npm link
Making an Upstart job is very easy. Create a file in /etc/init/node-simple-http-daemon.conf with the following contents:

# /etc/init/node-simple-http-daemon.conf

start on started network
stop on stopping network

expect daemon

exec https-proxy-daemon
Now you can:

$ sudo start node-simple-http-daemon # Start the job
$ initctl –system node-simple-http-daemon # Check the job status
$ sudo reload node-simple-http-daemon # Send SIGHUP (restart the workers)
$ sudo stop node-simple-http-daemon # Stop the job
Next Steps
You may want to modify the daemon to give up spawning workers when they’re getting killed too frequently (spinning).

I can’t emphasize enough how important it is to have adequate logging in your application. Make sure to check out node-bunyan.

Submitted by: Fardjad Davari

Try this tutorial on an SSD cloud server.
Includes 512MB RAM, 20GB SSD Disk, and 1TB Transfer for $5/mo! Learn more.

Create your account or sign-in

Comparison Chart
Network Status
Articles & Tutorials
Get Paid to Write
Suggest an Article
Referral Program
Badges & Logos
The Shop
Getting Started
One-Click Install Applications
What is Cloud Hosting?
Control Panel Overview
Deploy a Virtual Server
Set-Up SSH Keys
Install Git on Ubuntu
How to Install Ruby on Rails
How to Install LAMP Stack
Set-Up a Host Name
©2011-2013 DigitalOcean™, Inc. All Rights Reserved. Terms & Privacy. Security.
Get Started

 1,688 total views