Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to set up the Node.js available in the production environment on Ubuntu 14.04

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how to set up the Node.js available in a production environment on Ubuntu 14.04. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Set up the Node.js preface available in the production environment on Ubuntu 14.04

Node.js is an open source JavaScript runtime environment that developers can use to build server-side applications and web applications conveniently. Node.js can be run on Linux, OS X, FreeBSD, and Windows, and applications running on it are written in JavaScript. Node.js applications can be run on the command line, but the purpose of this article is to run Node.js applications as services, so that these applications can be automatically restarted when the system restarts or encounters errors to meet the needs of the production environment.

This article will set up an online Node.js environment that consists of two Ubuntu 14.04 servers: one running Node.js applications managed by PM2, and the other a pedal server, which allows users to log in to the application server through a Nginx reverse proxy.

There is a CentOS version of this tutorial, which can be found here.

prerequisite

The two Ubuntu 14.04s in this tutorial are connected through a private network (in the same data center). The two servers are named as follows:

App: servers with Node.js Runtime, Node.js applications, and PM2 installed

Web: pedal server with Nginx installed (as a reverse proxy). The user accesses the local IP to connect to the app server.

You can also use a single server to complete this tutorial, just replace all the places in the tutorial that involve the private IP of the app server with native IP (127.0.0.1).

The diagram of the entire deployment is as follows:

Before starting the operation, you need to set up ordinary non-root users with sudo privileges on both servers, and we need to log in to the server with this user name. If you haven't already set it up, you can refer to our Ubuntu 14.04 initial configuration tutorial.

If you want to access the web server through a domain name instead of IP, you need to purchase a domain name, and then refer to the following tutorial to complete the settings:

How To Set Up a Host Name with DigitalOcean

How to Point to DigitalOcean Nameservers From Common Domain Registrars

Once the above conditions are met, go to the following steps to start installing Node.js on the app server.

Install Node.js

We will install the latest LTS version of Node.js on the app server.

On the app server, run the apt-get update command:

Sudo apt-get update12

Then install git (git is required for npm installation):

Sudo apt-get install git12

Go to the Node.js website to find the download link for the Linux package (.tar.xz) and right-click to copy the address. The latest LTS version at the time of writing this tutorial is 4.2.3. If you want to install the latest stable version, you can go to the stable version download page to get the download address.

Go to the home directory and download the source code of Node.js with wget:

Cd ~ wget https://nodejs.org/dist/v4.2.3/node-v4.2.3-linux-x64.tar.gz1234

After the download is completed, extract it to the node directory:

Mkdir nodetar xvf node-v*.tar.?z-- strip-components=1-C. / node1234

After unzipping, the compressed package is useless. You can go back to the directory you just downloaded and delete the compressed package you downloaded earlier:

Cd ~ rm-rf node-v*1234

Then, we will configure the global prefix of npm, which is used to create the symbolic link (symbolic link) of the Node package. Here we set the default directory to / usr/local:

Mkdir node/etcecho 'prefix=/usr/local' > node/etc/npmrc1234

Now, move the binaries for node and npm to the installation path (our installation path is / opt/node):

Sudo mv node / opt/12

Then, set the owner of the file to root:

Sudo chown-R root: / opt/node12

Then, set symbolic links for the binaries for node and npm. We are using / usr/local/bin:

Sudo ln-s / opt/node/bin/node / usr/local/bin/nodesudo ln-s / opt/node/bin/npm / usr/local/bin/npm1234

Finally, verify that Node is installed correctly:

Node-v12

Thus, the installation of the Node.js runtime is complete. Now let's start writing our Node.js application.

Create a Node.js application

We will create a simple "Hello World" application that returns "Hello World" for all HTTP requests. You can also deploy your own application directly, just make sure that the IP address and port on which your application listens is correct.

We want the application to respond to requests from the reverse proxy server "web", so we need to configure communication between servers in the private network on the app server. You need to know the private network address of the app server.

For DigitalOcean users, the private IP of your droplet can be queried in the Metadata service-- use the curl command on the app server to get this IP:

Curl-w "\ n" http://169.254.169.254/metadata/v1/interfaces/private/0/ipv4/address 12

The result returned by this command is the private IP of the server, which is copied for later use.

Hello World code

Now, create our Node.js application. This tutorial uses the vi editor and creates an application called hello.js:

Cd ~ vi hello.js1234

Copy the following code to a file. Remember to replace the private IP of the app server (the contents of the two APP_PRIVATE_IP_ADDRESS sections) with your own. The port used in the following definition is 8080. If necessary, you can also change it to your own (non-admin port only, that is, 1024 or above):

Hello.js

Var http = require ('http'); http.createServer (function (req, res) {res.writeHead (200,{' Content-Type': 'text/plain'}); res.end (' Hello World\ n');}) .birthday (8080, 'APP_PRIVATE_IP_ADDRESS'); console.log (' Server running at http://APP_PRIVATE_IP_ADDRESS:8080/');1234567)

Save exit.

The application can listen on specified IP addresses and ports and return "Hello World" and 200 HTTP status codes. Currently, the application can only be accessed by servers on the same private network-such as our web server.

Test the application (optional)

To test the application, type the following command on the app server:

Node hello.js12

Note: when you run the Node.js application with this instruction, other commands sent to the server will be blocked. At the end of the test, remember to exit the application with CTRL+C.

Open another terminal process, connect to the web server, and access the private IP of the app server from that server. Let's use the curl command (remember to replace APP_PRIVATE_IP_ADDRESS and port 8080 with your own):

Curl http://APP_PRIVATE_IP_ADDRESS:808012

If the output is as follows, the application runs normally and the test passes:

Output:Hello World123

Otherwise, please go back and check the running status of the Node.js application and whether the IP address and port configured above are incorrect.

After the test is complete, go back to the app server and CTRL+C to exit the application.

Install PM2

PM2 is a process manager for Node.js applications. It is convenient for PM2 to manage Node.js applications as daemons (services).

We will install PM2 on the app server using NPM (the Node package module). Enter the following command:

Sudo npm install pm2-G12 uses PM2 to manage applications

The use of PM2 is simple. We will introduce some basic uses of PM2.

Start the application

First, start our hello.js with the pm2 start command, which allows the application to run in the background:

Pm2 start hello.js12

This command also adds the application to the list of processes in PM2. Each time you start an application with PM2, the terminal returns the following output:

│: ┌─┬────┬─┐│ App name │ id mode │ PID │ status │ restarted │ uptime │ memory │ watching │├─ ─┼────┼─┤│ hello │ 0 │ fork │ 5871 │ online │ 0 │ 0s │ 9.012 MB │ disabled │└─┴─ ───┴─┘ 1234567

As you can see above, PM2 automatically assigns an application name (that is, the file name of the application minus the .js suffix) and a PM2 id to the running application. PM2 also maintains other information, such as the process's PID, current state, and memory usage.

Applications running under PM2 will be automatically restarted if they crash or are kill. If you want to be able to run automatically after a system restart (boot or reboot), you can use the startup subcommand of PM2.

The startup subcommand creates a startup script that opens PM2 and all the processes it manages when the server starts. You need to specify the operating system in the command, which in this tutorial is ubuntu:

Pm2 startup ubuntu12

In the returned result, the last line is a command that we need to execute manually once (with superuser permissions):

Output: [PM2] You have to run this command as root [PM2] Execute the following command: [PM2] sudo su-c "env PATH=$PATH:/opt/node/bin pm2 startup ubuntu-u sammy-- hp / home/sammy" 12345

Copy it down, run it, and realize the function that the application can start automatically after the system is restarted:

Other uses of sudo su-c "env PATH=$PATH:/opt/node/bin pm2 startup ubuntu-u sammy-- hp / home/sammy" 12PM2 (optional)

PM2 also has some other sub-options that can be used for application management and information query. The help page for PM2 can be called up by running pm2, which lists more detailed usage. This article is just a brief introduction.

Stop the application (specified with the application name or PM2 id):

Pm2 stop example12

Restart the application (specified by the application name or PM2 id):

Pm2 restart example12

List the applications in the current management:

Pm2 list12

Details about the specified application (specified with the application name or PM2 id):

Pm2 info example12

Displays application status, CPU, memory usage:

Pm2 monit12

Now that we have finished launching the Node.js application and setting up the PM2, we can go to the web server to set up the reverse proxy.

Set up reverse proxy server

We will use Nginx to reverse the user's access request to the private IP of the app server. This tutorial will set up a Nginx from scratch. If you have already configured Nginx on your system, you can directly copy and paste the following location parts into your own configuration file (just don't conflict with the existing configuration).

Go to the web server and update the software list:

Sudo apt-get update12

Install Nginx with apt-get:

Sudo apt-get install nginx12

Open the Nginx configuration file with vi:

Sudo vi / etc/nginx/sites-available/default12

Delete the original content and copy and paste the following content. Where the server_name part is set to the native IP or domain name of the web server, and the APP_PRIVATE_IP_ADDRESS is set to the private IP of the app server. If port 8080 is not used in the above steps, it also needs to be modified:

/ etc/nginx/sites-available/default

Server {listen 80; server_name example.com; location / {proxy_pass http://APP_PRIVATE_IP_ADDRESS: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;} 123456789101112131415

The above configuration forwards the request to access the root address of the web server to the app server, that is, for access to http://example.com/, the request is forwarded to port 8080 of APP_PRIVATE_IP_ADDRESS, and the content returned by the Node.js application on it is returned to the browser through the web server.

We can also add more retweets to the web server by adding location content blocks. For example, if we want to forward all access to http://example.com/app2 to port 8081 of APP_PRIVATE_IP_ADDRESS, we can add the following:

Location / app2 {proxy_pass http://APP_PRIVATE_IP_ADDRESS: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;} 123456789

After editing, save and exit.

Restart Nginx on the web server:

Sudo service nginx restart12

If our Node.js application is running properly, and the application configuration and Nginx configuration are correct, we will be able to access our application when we access the web server in the browser. Now go to the browser and enter the public IP or domain name of the web server.

Thank you for reading! This is the end of the article on "how to set up the Node.js available in the production environment on Ubuntu 14.04". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report