Lemp Environment collocation Tutorial (ubuntu16.04+nginx+mysql+php)

Source: Internet
Author: User
Tags error code flush fpm install php parent directory socket file permissions install wordpress


Get a new installed Linux server, how to configure a Web server that can parse Dynamic Web script? I believe this is a problem that many people will have. This article takes you step-by-step to build a Web server that gives the Lemp technology stack, and makes it possible to run PHP, Nodejs, and other languages properly.
The so-called Lemp technology stack, as the name implies is actually Linux, Nginx, MySQL, PHP portfolio. Of course, if you like, you can not nginx, but to choose Apache, this is the so-called lamp technology stack.

This article uses the Linux version for the Ubuntu 16.04 64-bit version.

Ubuntu Server Basic Settings

Using root to log on to the server
First we need to log in to the server with root, and of course you can choose a lot of tools, such as SECURECRT or putty. Login here via SSH command line:

local$ SSH root@server_ip_address
The previous local$ representation is in the local machine operation, on the server side, the prompt will resemble root@my-remote-server:~$ this form, see behind.
New Super User Rights user
The root user is powerful, but it's too powerful to be safe, so normally we need to create a new user and then set up Superuser (Superuser) privileges so that we can do all sorts of things safely.
Log in using the root user to do the following:

root@my-remote-server:~$ AddUser Dennis
root@my-remote-server:~$ Usermod-ag sudo Dennis
This is where the newly created user is added to the sudo user group and has the power of the superuser. More detailed information can be referenced in this tutorial.
Then we can log on as a newly created user:

root@my-remote-server:~# Su-dennis
Set SSH key authentication
Each time we login to the server via SSH, we need to enter a password, which is the way of password authentication. For convenience, we can login via SSH key authentication. After setting, we do not need to enter the password, you can directly ssh to the server.
For example, local machines need to connect to remote servers locally, and we first need to generate SSH key on the locals:

After execution, you will see that two files are generated in the/users/localuser/.ssh/directory: Id_rsa and Id_rsa.pub, respectively, the private key and the public key.
You then need to configure the public key to a remote server. A simpler way is to use the Ssh-copy-id tool. If you are on a Mac, you can install SSH-COPY-ID-FOR-OSX. Execute after Setup completes

Ssh-copy-id dennis@server_ip_address
The configuration is complete. Another way is to manually configure, you can refer to the tutorial here to operate. The article also details the SSH key more content, available for reference.
Disable Password Authentication logon method
For security reasons, we can also disable the way password is logged in. Modify configuration file

sudo vim/etc/ssh/sshd_config
Modify the following properties:

Passwordauthentication No
You will then need to update the following sshd configuration:
sudo systemctl reload sshd
OK, currently can not use the password way to log in, can only be authenticated by the SSH key above the way to log in to the server.
Lemp Environment Construction and configuration
Install Nginx
Installing the software on Ubuntu is simple, using Apt-get. Note that you need to add sudo to the front because of permissions issues.

sudo apt-get update
sudo apt-get install Nginx

Step on the pit to remind

An error occurred while installing Nginx

dennis@my-remote-server:~$ sudo apt-get install Nginx
Reading Package Lists ... Done
Building Dependency Tree
Reading state information ... Done
Nginx is already the newest version (1.10.0-0ubuntu0.16.04.2).
0 upgraded, 0 newly installed, 0 to-remove and not upgraded.
2 not fully installed or removed.
After this operation, 0 B of additional disk space would be used.
Do your want to continue? [y/n]
Setting up Nginx-core (1.10.0-0ubuntu0.16.04.2) ...
Job for Nginx.service failed because process exited with error code. "Systemctl status Nginx.service" and "Journalctl-xe" for details.
Invoke-rc.d:initscript Nginx, action "start" failed.
Dpkg:error Processing Package Nginx-core (--configure):
Subprocess installed post-installation script returned error exit status 1
Dpkg:dependency problems prevent configuration of Nginx:
Nginx depends on Nginx-core (>= 1.10.0-0ubuntu0.16.04.2) | Nginx-full (>= 1.10.0-0ubuntu0.16.04.2) | Nginx-light (>= 1.10.0-0ubuntu0.16.04.2) | Nginx-extras (>= 1.10.0-0ubuntu0.16.04.2); However
Package Nginx-core is not configured yet.
Package Nginx-full is not installed.
Package Nginx-light is not installed.
Package Nginx-extras is not installed.
Nginx depends on Nginx-core (<< 1.10.0-0ubuntu0. | Nginx-full (<< 1.10.0-0ubuntu0. | Nginx-light (<< 1.10.0-0ubuntu0. | Nginx-extras (<< 1.10.0-0ubuntu0.; However
Package Nginx-core is not configured yet.
Package Nginx-full is not installed.
Package Nginx-light is not installed.
Package Nginx-extras is not installed.
Dpkg:error Processing Package Nginx (--configure):
Dependency Problems-leaving unconfigured
Errors were encountered while processing:

E:sub-process/usr/bin/dpkg returned an error code (1)
Cause analysis

Google a bit, found that this error, generally should be due to other applications occupy 80 ports. You can look at this:

dennis@myserver:~$ sudo netstat-nlp
Sudo:unable to resolve host MyServer
[sudo] password for Dennis:
Active Internet connections (only servers)
Proto recv-q Send-q Local address Foreign address State Pid/program Name
TCP 0 0* LISTEN 132/rpcbind
TCP 0 0* LISTEN 332/apache2
TCP 0 0* LISTEN 269/sshd
TCP 0 0* LISTEN 454/master
TCP6 0 0:: £ º::* LISTEN 132/rpcbind
TCP6 0 0:::::* LISTEN 269/sshd
Sure enough, 80 ports are taken up by the default Apache, so you need to kill the apache2 that consumes 80 ports:

sudo kill-9 332

Setting locale failed error occurred while running apt-get command update or install software

Perl:warning:Setting locale failed.
Perl:warning:Please Check that your locale settings:
LANGUAGE = (unset),
Lc_all = (unset),
Lc_ctype = "en_US." UTF-8 ",
LANG = "en_US." UTF-8 "
are supported and installed on your system.
Perl:warning:Falling back to the standard locale ("C").
Locale:cannot set LC_CTYPE to default locale:no such file or directory
Locale:cannot set Lc_messages to default locale:no such file or directory
Locale:cannot set Lc_all to default locale:no such file or directory


sudo ap-get update
Apt-get Install Language-pack-en
Nginx Common Directory
/var/www/html: The default directory for saving Web page content
Server Configuration
/etc/nginx:nginx configuration directory. All Nginx related configuration files are here.
/etc/nginx/nginx.conf:nginx the master configuration file for global default settings.
/etc/nginx/sites-available: A separate profile for each "server blocks". The configuration files here are not used directly, and only soft connections to the site-enabled configuration will actually take effect.
/etc/nginx/sites-enabled/: A separate profile for each "server blocks". From the sites-available chain.
/etc/nginx/snippets: Some configuration script fragments.
Server log
/var/log/nginx/access.log: All requests that interact with the Web service are saved by default.
Error log for/var/log/nginx/error.log:nginx

1. Check the Nginx configuration file for problems:

dennis@my-remote-server:~$ sudo nginx-t-c/etc/nginx/nginx.conf
Nginx:the configuration file/etc/nginx/nginx.conf syntax is OK
Nginx:configuration file/etc/nginx/nginx.conf Test is successful
2. Stop Apache Service
There are a number of ways to stop the Apache service, specific reference ubuntu-linux-start-restart-stop-apache-web-server. The more commonly used are:

Sudo/etc/init.d/apache2 stop

$ sudo apache2ctl stop

3. Cancel Apache from start
In Ubuntu, Apache can be set to start by default, which means you'll get up again after you kill. You can cancel your startup by using the following command:

sudo update-rc.d-f apache2 Remove
Reply from startup requires:

sudo update-rc.d apache2 defaults

4. Nginx Start and stop

Like the start and stop of Apache, there are several ways to start and stop Nginx services, which are commonly used:

To stop your Web server, can type:
sudo systemctl stop Nginx
To start the Web server as it is stopped, type:
sudo systemctl start nginx
To stop and then start the service again, type:
sudo systemctl restart Nginx
If you are simply making configuration changes, Nginx can often reload the without dropping. To does this, this command can be used:
sudo systemctl reload Nginx
By default, Nginx are configured to start automatically the server boots. If This isn't what you want, can disable this behavior by typing:
sudo systemctl disable Nginx
To re-enable the "service" to "Start up" at boot, can type:
sudo systemctl enable Nginx

Sudo/etc/init.d/nginx restart
sudo service nginx restart
5. View the native IP address

IP Addr Show Venet0 | grep inet | awk ' {print $} ' | Sed ' s/\/.*$//'
Where venet0 may be eth0, it can be seen through IP addr or ifconfig.
Or you can do this:

dennis@my-remote-server:/$ Curl http://icanhazip.com

6. Check the status of Nginx:

dennis@my-remote-server:/var/www$ sudo systemctl status nginx
Nginx.service-a High Performance Web server and A reverse proxy server
Loaded:loaded (/lib/systemd/system/nginx.service; enabled; vendor preset:enabled)
Active:active (running) since Wed 2016-08-17 CST; 2h 43min ago
Main pid:5221 (Nginx)
├─5221 nginx:master process/usr/sbin/nginx-g daemon on; Master_process on
├─15622 Nginx:worker Process
└─15623 Nginx:worker Process
Aug 14:39:33 my-remote-server systemd[1]: Stopped A High Performance Web server and a reverse proxy server.
Aug 14:39:33 My-remote-server systemd[1]: Starting A High Performance Web server and a reverse proxy server ...
Aug 14:39:33 my-remote-server systemd[1]: nginx.service:Failed to read PID from File/run/nginx.pid:invalid argument
Aug 14:39:33 My-remote-server systemd[1]: Started A high performance Web server and a reverse proxy server.
Aug 15:52:19 my-remote-server systemd[1]: Reloading A High Performance Web server and a reverse proxy server.
Aug 15:52:19 My-remote-server systemd[1]: Reloaded A High Performance Web server and a reverse proxy server.
Aug 16:34:05 my-remote-server systemd[1]: Reloading A High Performance Web server and a reverse proxy server.
Aug 16:34:05 My-remote-server systemd[1]: Reloaded A High Performance Web server and a reverse proxy server.

installing MySQL


sudo apt-get update
sudo apt-get install Mysql-server

sudo mysql_secure_installation
To view the version of MySQL:

Previous versions in 5.7.6:

sudo mysql_install_db
5.7.6 and later versions:
sudo mysqld--initialize

This step is usually done if it is installed through Apt-get as described above. As a result, you will be prompted with the following error:

[ERROR]--initialize specified but the data directory has files in it. Aborting.
MySQL Start and stop

Sudo/etc/init.d/mysql start
Sudo/etc/init.d/mysql stop
Sudo/etc/init.d/mysql restart


sudo start MySQL
sudo stop MySQL
sudo restart MySQL

This method uses the "upstart" (in fact, the soft connection of the/etc/init.d/mysql).
Test connection

The Mysqladmin-p-u root version command can be used to test whether the MySQL connection is normal.

Dennis@my-remote-server:/var/www/html$ mysqladmin-p-U root version
Enter Password:
Mysqladmin Ver 8.42 distrib 5.7.13, for Linux on x86_64
Copyright (c), 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark the Oracle Corporation and/or its
Affiliates. Names may trademarks of their respective
Server version 5.7.13-0ubuntu0.16.04.2
Protocol version 10
Connection Localhost via UNIX socket
UNIX Socket/var/run/mysqld/mysqld.sock
uptime:19 min sec
Threads:1 questions:8 Slow queries:0 opens:115 Flush tables:1 Open tables:34 queries per second avg:0.006

Installing PHP

sudo apt-get-y install php7.0-fpm php7.0-mysql

Configure PHP settings

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

Open the configuration file, locate the Cgi.fix_pathinfo, and modify it to:


Then restart the PHP environment:

sudo systemctl restart PHP7.0-FPM
Nginx Configuration supports PHP
To open the Nginx service block configuration file:
sudo vim/etc/nginx/sites-available/default

Modify the file as (specific modifications can refer to the instructions here):

server {
Listen default_server;
Listen [::]:80 default_server;
Index index.php index.html index.htm index.nginx-debian.html;
server_name server_domain_or_ip;
Try_files $uri $uri/= 404;
Location ~ \.php$ {
Include snippets/fastcgi-php.conf;
Fastcgi_pass Unix:/run/php/php7.0-fpm.sock;
Location ~/\.ht {
Deny all;

After the save has been modified, you can use the sudo nginx-t command to confirm the correctness of the configuration file.
Then use the command sudo systemctl reload nginx restart Nginx.

Create a new file/var/www/html/info.php, which reads as follows:

Phpinfo ();

Then visit http://server_domain_or_IP/info.php to see the results.
Install wordpress application (optional)
Now that the LEMP environment has been set up, let's briefly introduce the process of installing the most popular blog program WordPress in this environment. This section is for informational purposes only and may not be installed if it is not required.
Database and Environment configuration
Create a database and a new database user
Mysql-u root-p
After successful login with password, execute the following SQL statement to create a database named WordPress


For security purposes, we create a separate user for this database:

GRANT all on wordpress.* to ' wordpressuser ' @ ' localhost ' identified by ' password ';
FLUSH privileges;

Configure Nginx

To open a configuration file:

sudo vim/etc/nginx/sites-available/default

Make the following modifications (refer to the instructions here)

server {
. . .
Location =/favicon.ico {log_not_found off; access_log off;}
Location =/robots.txt {log_not_found off, access_log off, allow all;
Location ~* \. (css|gif|ico|jpeg|jpg|js|png) $ {
Expires Max;
Log_not_found off;
. . .

Make the following modifications to the Try_files:

server {
. . .
#try_files $uri $uri/= 404;
Try_files $uri $uri//index.php$is_args$args;
. . .
Then check the correctness of the configuration file and restart Nginx:

sudo nginx-t
If no errors were reported, Reload Nginx by typing:
sudo systemctl reload Nginx
Install an additional PHP extension

sudo apt-get update
sudo apt-get install php-curl php-gd php-mbstring php-mcrypt php-xml php-xmlrpc
After installation, you need to restart the PHP-FPM for the new settings to take effect.

sudo systemctl restart PHP7.0-FPM

Install WordPress

Get and install the WordPress source code

Curl-o https://wordpress.org/latest.tar.gz
Tar xzvf latest.tar.gz
sudo cp-a/tmp/wordpress/. /var/www/html
Adjust file permissions and ownership

sudo chown-r dennis:www-data/var/www/html
We also need to set Setgid to make the newly created file in the directory, and the parent directory have the same permissions:

sudo find/var/www/html-type d-exec chmod g+s {} \;
There is also a need for some special catalogs to be processed:

sudo chmod g+w/var/www/html/wp-content
sudo chmod-r g+w/var/www/html/wp-content/themes
sudo chmod-r g+w/var/www/html/wp-content/plugins
Set Secure key
We can use the official WordPress tools to generate secure key:

Curl-s https://api.wordpress.org/secret-key/1.1/salt/
After running, you get the following results:

Define (' Auth_key ', ' b?=x1eclla9c6f]%=8a$d^p=,y$+# ') | xv2fffo-sq8xy8m-a|6ie0_t-|! O.*esa ');
Define (' Secure_auth_key ', ' mf5cq|m{(twqqhk+_>d4ubj5vu|), c) 5^!wybq1wu+tbk8tfh]_<p#yz|x; t{l% ');
Define (' Logged_in_key ', ' (j<=p5my3?>bqmqwk!) O=r+|] =8q^hj/_+dro= ' -8XA[LBUQNT+WK2MJNLC $k &l ');
Define (' Nonce_key ', ' y,d2p24;-_g7-') (Tu<x0hepu:_ ({?) Ja4giah@#<wpivc=p%xwzb1.e|x#,l]1n2co ');
Define (' Auth_salt ', ') +fc8pf&fwd[*ux[| yxxf-*!ds$uuy3tczp|+-v_vt*-ox-6| A+a!] A*tjo^de= ');
Define (' Secure_auth_salt ', ' 4ms!kc> Y2*6fe+?; fe=>0br~cb5j; c/6sn177c (P%q) (q6a-{i&[n,2tn!ly. GgW ');
Define (' Logged_in_salt ', ' 0nu| | ~mix-++a;us3bwde2-=a2+8= ' C_ (6jd_hjpf@9ditiau--w[wfb}+:P |[ [+');
Define (' Nonce_salt ', ' f=umqao!jv (| #Di =a$z6 (L^_|Z=WTNI2/P8&LT;L7BO/IFIQX03!+HMQDA*6|HXOG3 ');
Copy to the wp-config.php file to replace the corresponding content.
Set database information and file operation permissions
wp-config.php file to modify the database information, and add Fs_method so that WordPress can access the file system for file read and write operations, which is useful when installing plug-ins.

Define (' db_name ', ' WordPress ');
/** MySQL Database Username * *
Define (' Db_user ', ' wordpressuser ');
/** MySQL Database Password * *
Define (' Db_password ', ' PASSWORD ');
Define (' Fs_method ', ' direct ');
Then we can visit the Http://server_domain_or_IP for WordPress installation.
Configuring multiple sites on a lemp environment
Typically we need to deploy multiple sites on a Web server, using multiple different domain names. The following is a detailed description of how to configure on our lemp environment.
Set up a new document directory
By default, Nginx on Ubuntu has created a server block by default and its document directory is/var/www/html (this default server block is used when we install WordPress above).
If we need to deploy multiple sites, we need to create several different server blocks. If we need to deploy two sites:

So we need to set up two new document directories. For the sake of unification, we use the Xxx.com/html directory structure form:

sudo mkdir-p/var/www/example.com/html
sudo mkdir-p/var/www/test.com/html
Modify the permissions for these two document directories:

sudo chown-r $USER: $USER/var/www/example.com/html
sudo chown-r $USER: $USER/var/www/test.com/html
The environment variable $user is used here, please make sure that you do not use the root account to operate.

dennis@my-remote-server:~$ Echo $USER

The document directory should now be configured. If necessary, we can set the permissions of the upper directory with the following command:

sudo chmod-r 755/var/www

The caveat is that you don't need to worry about whether these two test domain names are accessible at this time, and then we'll explain how to access both test domains in a local browser.
Create test files for each site

Create a file/var/www/example.com/html/index.html that reads:

<title>welcome to Example.com!</title>

Similarly, create a file/var/www/test.com/html/index.html that reads:

<title>welcome to Test.com!</title>
Create a server block file for each site
As mentioned earlier, by default Nginx has been configured with a default server block, so we can copy the default server block profile and modify it slightly:

sudo cp/etc/nginx/sites-available/default/etc/nginx/sites-available/example.com
Open File:

sudo vim/etc/nginx/sites-available/example.com
Its contents are as follows:

server {
Listen default_server;
Listen [::]:80 default_server;
Index index.html index.htm index.nginx-debian.html;
server_name _;
Try_files $uri $uri/= 404;

The contents of the amendment are slightly modified, and the following changes are as follows:

server {
Listen 80;
Listen [::]:80;
Index index.html index.htm index.nginx-debian.html;
server_name example.com www.example.com;
Try_files $uri $uri/= 404;

The main modifications were made in several places:

Removed the Default_server word. There can be only one default_server configuration on a single server, so we keep the system initially set to the default setting.
Modify the root directory.
Modify server_name.
Similar modifications are made for the second site test.com.

sudo cp/etc/nginx/sites-available/example.com/etc/nginx/sites-available/test.com
sudo vim/etc/nginx/sites-available/test.com
Activate server block for two sites
Use the following command:

sudo ln-s/etc/nginx/sites-available/example.com/etc/nginx/sites-enabled/
sudo ln-s/etc/nginx/sites-available/test.com/etc/nginx/sites-enabled/
These files (links) are located in the Active Directory. So far we have 3 Active server blocks. The server determines which directory to access according to listen Directives and server_name.
example.com: Responding to requests from example.com and www.example.com
Test.com: Responding to requests from test.com and www.test.com
Default: The response does not have a request that matches the 80 port above two rules.
In addition, you need to set the server_names_hash_bucket_size in the Nginx configuration file/etc/nginx/nginx.conf:

. . .
Server_names_hash_bucket_size 64;
. . .
Then check the correctness of the Nginx configuration file:
sudo nginx-t
Restart the nginx to make the changes effective:
sudo systemctl restart Nginx
More instructions on Nginx can refer to this tutorial.
Local test

Since the two domain names example.com and test.com are not our real domain names, it is necessary to test the access with the local machine to modify the hosts.
Take Mac as an example, modify the/etc/hosts file: localhost
. . .
XXX.XXX.XXX.XXX example.com www.example.com
XXX.XXX.XXX.XXX test.com www.test.com

The front XXX.XXX.XXX.XXX is the server's extranet IP.
Now we have direct access to example.com and test.com to view these two sites.
Tips: About the real domain name related settings, there is a need to refer to this article.
Install and deploy Node.js applications on Ubuntu
Install Node.js
Install by Apt-get

You can use Apt-get to install Node.js on Ubuntu:

sudo apt-get update
sudo apt-get install Nodejs
sudo apt-get install NPM

However, there are two problems with Node.js installed in this way:
Nodejs's version is older, and now I see v4.2.6.
In Ubuntu, because the name node is occupied by other programs, you need to use Nodejs to use Node.js.
Such as:

dennis@my-remote-server:~$ Nodejs--version

Install via NVM

NVM, as the name suggests, is the Node.js version Manager ("Node.js version Manager"), which allows us to install multiple versions of Node.js and easily switch freely.

To install NVM, you first need to install some dependent packages:

sudo apt-get update
sudo apt-get install build-essential Libssl-dev

Then get the installation script from NVM's GitHub repo.

CURL-SL Https://raw.githubusercontent.com/creationix/nvm/v0.31.4/install.sh-o install_nvm.sh

The latest version I've seen is 0.31.4. You can change it to the current version.
Then execute the script:

Bash install_nvm.sh the script will install NVM in the ~/.NVM directory and make some necessary changes to the ~/.profile file, and we need to make the changes take effect immediately:

SOURCE ~/.profile

You can then view the currently available Node.js versions by using the following command:

dennis@my-remote-server:~$ NVM Ls-remote

The latest version is v6.4.0.

Then install the latest version with the following command:

NVM Install 6.4.0

Typically, NVM chooses the most recently installed version to use. Of course, we can also use the NVM using 6.4.0 command to switch versions.
You can use the command NVM LS to view the version that the current environment has installed:

dennis@my-remote-server:~$ NVM ls
-> v6.4.0
Default-> 6.4.0 (-> v6.4.0)
Node-> stable (-> v6.4.0) (default)
Stable-> 6.4 (-> v6.4.0) (default)
Iojs-> N/A (default)

Install by adding a PPA

This way for the time being do not introduce, have the interest to refer to the tutorial here.
Create a simple Node.js application

We create a simple node.js application for testing. Create a new file Hello.js:

#!/usr/bin/env Nodejs
var http = require (' http ');
Http.createserver (function (req, res) {
Res.writehead ({' Content-type ': ' Text/plain '});
Res.end (' Hello world\n ');
}). Listen (8080, ' localhost ');
Console.log (' Server running at http://localhost:8080/');

Modify its executable permissions and execute:

chmod +x./hello.js

You can see the following tips:

1Server running at http://localhost:8080/

Indicates that the service is up and running, and that the application can be accessed by http://:8080/IP_address:8080.
Using PM2 to manage Node.js applications
PM2 is an excellent node.js application management tool that makes it easy to manage node.js applications on the server and keep it running in the background.
Install PM2

sudo npm install-g pm2

Using PM2

Start Node.js Application

You can use the PM2 Start command to start the example application that we just created.

dennis@my-remote-server:~$ PM2 Start Hello.js
[PM2] Spawning PM2 daemon
[PM2] PM2 successfully daemonized
[PM2] Starting hello.js in Fork_mode (1 instance)
[PM2] Done.
│app name│id│mode│pid│status│restart│uptime│memory│watching│
│hello│0│fork│8689│online│0│0s│14.566 mb│disabled│
Use "PM2 show <id|name>" To get more details about a app

Set up server restart auto Start application

It is worth mentioning that the application initiated by PM2 will be restarted automatically if it occurs crash or is killed by another program. Note, however, that you need to do a little extra work to get your application up and running after the system restarts. This is the function of the startup command:

dennis@my-remote-server:~$ PM2 Startup Systemd
[PM2] You are have to run this command as root. Execute the following command:
sudo su-c "env path= $PATH:/home/dennis/.nvm/versions/node/v6.4.0/bin pm2 startup Systemd-u Dennis"

After execution, you will see the last line, which is a command:

sudo su-c "env path= $PATH:/home/dennis/.nvm/versions/node/v6.4.0/bin pm2 startup Systemd-u Dennis"

Run it. After the success, we can view the status by command sudo systemctl status PM2:

dennis@my-remote-server:~$ sudo systemctl status pm2
PM2.SERVICE-PM2 Next Gen Process Manager for Node.js
Loaded:loaded (/etc/systemd/system/pm2.service; enabled; vendor preset:enabled)
Active:active (running) since Fri 2016-08-19 CST; 3min 9s ago
process:10726 execstart=/usr/local/lib/node_modules/pm2/bin/pm2 Resurrect (code=exited, Status=0/SUCCESS)
Main pid:10732 (PM2 v1.1.3:god)
├─10732 PM2 V1.1.3:god Daemon
└─10742 Node/home/dennis/hello.js
Aug 12:02:46 my-remote-server pm2[10726]: [PM2] Resurrecting
Aug 12:02:46 my-remote-server pm2[10726]: [PM2] Restoring processes located-in/home/dennis/.pm2/dump.pm2
Aug 12:02:46 my-remote-server pm2[10726]: [PM2] Process/home/dennis/hello.js restored
Aug 12:02:46 my-remote-server pm2[10726]: ┌──────────┬────┬──────┬───────┬────────┬─────────┬────────┬─────────────┬──────────┐
Aug 12:02:46 my-remote-server Pm2[10726]:│app Name│id│mode│pid│status│restart│uptime│memory│wa Tching│
Aug 12:02:46 my-remote-server pm2[10726]: ├──────────┼────┼──────┼───────┼────────┼─────────┼────────┼─────────────┼──────────┤
Aug 12:02:46 my-remote-server pm2[10726]:│hello│0│fork│10742│online│0│0s│14.566 Mb│di Sabled│
Aug 12:02:46 my-remote-server pm2[10726]: └──────────┴────┴──────┴───────┴────────┴─────────┴────────┴─────────────┴──────────┘
Aug 12:02:46 my-remote-server pm2[10726]: Use ' PM2 show <id|name> ' to get more details about a app
Aug 12:02:46 My-remote-server systemd[1]: Started PM2 Next Gen process Manager for Node.js.
For the Systemctl command, it is highly recommended to take a look at this tutorial.
Step on the pit to remind

If the following error occurs:

dennis@my-remote-server:~$ sudo su-c "env path= $PATH:/home/dennis/.nvm/versions/node/v6.4.0/bin pm2 startup Systemd-u Dennis--hp/home/dennis "
[PM2] Generating System init script In/etc/systemd/system/pm2.service
[PM2] Making script booting at startup ...
[PM2]-systemd-using the command:
Su dennis-c "pm2 dump && pm2 kill" && su root-c "systemctl daemon-reload && systemctl enable PM2 && systemctl Start PM2 "
Command failed:su dennis-c "PM2 dump && pm2 kill" && su root-c "systemctl daemon-reload && Syst Emctl Enable PM2 && systemctl start PM2 "
/usr/bin/env: ' node ': No such file or directory
-----Are you to sure you with the right platform command line option? Centos/redhat, Amazon, Ubuntu, Gentoo, Systemd or Darwin?

It may be that our node is the reason for using NVM installation. Add a soft connection to the/usr/bin/node.

sudo ln-s/home/dennis/.nvm/versions/node/v6.4.0/bin/node/usr/bin/node

PM2 Common Commands

Stop application

PM2 Stop app_name_or_id

Restart Application

PM2 Restart app_name_or_id

Enumerate applications

PM2 List

View Application Details

PM2 Info Example

Monitoring applications

PM2 Monit

Using Nginx as a reverse proxy for node.js applications

Creating Node.js Applications

We already have a hello.js application, similar to this one, and then create a foo.js application. Create a file foo.js with the following code:

#!/usr/bin/env Nodejs
var http = require (' http ');
Http.createserver (function (req, res) {
Res.writehead ({' Content-type ': ' Text/plain '});
Res.end (' Foo bar\n ');
}). Listen (8081, ' localhost ');
Console.log (' Server running at http://localhost:8081/');

Listening on port 8081. To start the application:

PM2 Start Foo.js

This time we see that there are already two node.js applications running:

dennis@my-remote-server:~$ PM2 List
│app name│id│mode│pid│status│restart│uptime│memory│watching│
│hello│0│fork│10742│online│0│46m│21.570 mb│disabled│
│foo│1│fork│10897│online│0│8s│20.051 mb│disabled│
Use "PM2 show <id|name>" To get more details about a app

Set Nginx

As we said earlier, the default profile for Nginx is/etc/nginx/sites-available/default. We have created two new sites that correspond to the following configuration files:


Here we can modify the default configuration, or we can choose to modify the configuration of any one domain name. Let's take example.com as an example.
Remove the contents of the/etc/nginx/sites-available/example.com file and modify it to read:

server {
Listen 80;
server_name example.com;
Proxy_pass http://localhost:8080;
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;

Reload the Nginx configuration to make it effective:

sudo systemctl restart Nginx

To explain briefly, the function of this configuration is to listen to the server's 80 ports and reverse proxy to port 8080, which is our Hello application. That is, when the user accesses the http://example.com/through the browser, the user request will be sent to our hello.js application, the word "Hello World" will be displayed on the page.
Multiple application settings
If you need to set up access to multiple node.js applications, we can increase the configuration of the response in Nginx. Take the Foo.js application created above as an example:

Location/app2 {
        proxy_pass http://localhost:8081;
         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;
after using the command sudo systemctl restart nginx Restart Nginx, you can view the HTTP://EXAMPLE.COM/APP2 application's result "Foo Bar" by accessing Foo.js.
Write at the end
This article simply takes you to configure an available Web server, but there is bound to be a lot of knowledge points that are not involved. This requires us to go to Google more when we encounter problems. For example, the following topic, interested in the study can be their own.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.