Node.js – Lesson 4: Deploy application on server using git, configure Nginx and pm2

To deploy Node.js application in Internet we need server and domain name. We will use Ubuntu 18.04. On server install Node.js using commands:

curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
sudo apt-get install nodejs

Also we need to install Nginx web server to proxy http and https requests (from 80, 443 ports) to node application port.

sudo apt-get install nginx

We need to install Git if we want to deploy our application from git repository:

sudo apt-get install git

Next go to /home directory and use command:

git clone repositury_url

This command will clone all files from your git repository to server.

Next we need to install all dependencies from package.json:

npm install

And now we can run our application using command:

node index.js

But this command will stop work if our server will restart or if we close SSH connection to server. To run our application as daemon on server startm use special command pm2. Install it globally with Npm package manager:

sudo npm install pm2 -g

This program will run our node.js application in background:

pm2 start index.js

TO automatic start pm2 on system boot – generate startup script using command:

pm2 startup

And save configuration using command:

pm2 save

Node.js – Lesson 2: Start server, install dependencies

Next step of creating Node.js application is installing additional frameworks and dependencies that facilitate work with the project.

In our lesson we will use popular web framework “Express” and utility “Nodemon”, that will monitor for any changes in your source and automatically restart your server.

To install this dependencies in console write commands:

npm install express
npm install -D nodemon

Flag -D means that this is developer dependency and it not used in production project.

In section “scripts” write create script “start” and “dev”:

"start": "node index.js",
"dev": "nodemon index.js"

Node.js – Lesson 1: Create first application

First of all You need to install Node.js. On Windows computers go to https://nodejs.org/en/ website, download latest version and install it.

On Linux (Debian, Ubuntu Mint) add PPA repository of Node.js:

curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -

And install nodejs package

sudo apt-get install nodejs

To check Node.js version use command:

node -v
v12.18.3

Now let’s create new application. We will use Visual Studio Code editor. Open terminal and initialize NPM by command:

npm init

This command will create package.json configuration file. This file contains information about all packages, used in application.

Send Passwords and Restricted Data Securely

Never send your passwords and restricted data openly to other people! All social networks and messengers always save your data on servers and some third persons possibly can read your messages.

If you need to send secret data – send encrypted link that can only be viewed once. Don’t write from which service is this password, tell it to other person by phone or in other messenger.

In this case, the connection between the service and the password is broken and no one will be able to get the password, except to whom you sent the message.

One of such service, that encrypt your messages and delete it immediately after reading is: One Time Self Destructing Links (https://note.uax.cloud/en)

This service with open source and MIT license encrypt your message and generate special URL link, that you can send in social network or messenger to other people, after reading your message it will be automatically destroyed and no one will be able to read your message again.

Best php open source projects

1. Laravel

This is the best php-framework for new projects, web-sites, internet stores and other network projects.

The GitHub page of Laravel from where you can download and see the project code is: https://github.com/laravel/laravel

2. Symfony

Another PHP framework for web applications is Symfony. It is used by thousands of web applications (including BlaBlaCar.com and Spotify.com) and most of the popular PHP projects (including Drupal and Magento).GitHub Stars: 17.8k+

The GitHub page of Symfony from where you can download and see the project code is: https://github.com/symfony/symfony

3. Composer

Composer helps you declare, manage, and install dependencies of PHP projects.

GitHub Stars: 14.9k+

The GitHub page of Composer from where you can download and see the project code is: https://github.com/composer/composer

4. PHPMailer

PHPMailer is the best php library for sending email. Supports many mail servers including Gmail.

The GitHub page of PHPMailer from where you can download and see the project code is: https://github.com/PHPMailer/PHPMailer

Create React js application with Yarn

Very simple way to create new application on React JS using Yarn.

First of all install LTS version of Node.js on your computer from official site: https://nodejs.org/en/download/

Then also install stable version of Yarn from official site: https://yarnpkg.com/en/docs/install. (You can read here how to install Yarn in Ubuntu).

Next lets create new folder “react-app” with files of our application. In this folder create two empty files: index.html, package.json, and subfolder src such as on screenshot:

File index.html will have basic html markup:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>React App</title>
</head>
<body>
    <noscript>
        You need to enable JavaScript to run this app.
    </noscript>

    <div id="root"></div>

    <!-- Bundle -->
    <script src="./src/index.js"></script>
</body>
</html>

In subfolder src create file index.js, it will be main file of our react application:

Source code of index.js file:

import React from 'react';
import ReactDOM from 'react-dom';

const App = () => (
    <div>
        React App
    </div>
);
ReactDOM.render(<App />, document.getElementById('root'))

In file package.json write next code:

{
    "name": "ReactApp",
    "author": "Author Name",
    "license": "License Name",
    "homepage": "Author Website",
    "email": "Author Email",
    "version": "1.0.0",
    "scripts": {
      "start": "cross-env NODE_ENV=development parcel index.html --no-cache -d build/dev",
      "build": "cross-env NODE_ENV=production parcel build index.html --no-cache -d build/production"
    },
    "dependencies": {
      "@hot-loader/react-dom": "^16.8.4",
      "cross-env": "^5.2.0",
      "parcel-bundler": "latest",
      "react": "^16.8.4",
      "react-dom": "^16.8.4"
    },
    "devDependencies": {
      "babel-core": "^6.26.3",
      "babel-plugin-import": "^1.11.0",
      "babel-preset-react-app": "^7.0.1"
    }
  }

This file contains information about your project and all outsiders packages, used in your application.

That’s all, our simple react application ready. Now lets run it. Open your command line and go to your project folder:

To compose your application write command:

yarn

Yarn will download all packages and compose your application:

To run your program just enter command:

yarn start

This command builds your react application and start local server http://localhost:1234

Enter on this address in your browser and you will see your application:

Now if you change any source code in your project, it will be automatic changed in browser:

That’s all, finally look in folder build. There You will find compiled JavaScript code with your application which you can use in production.

React it’s simple! Good luck 😉

Install Yarn – Ubuntu 18.04

Спочатку імпортуйте ключ GPG репозиторію Yarn, використовуючи наступну команду, щоб включити репозиторій Yarn, використовуючи наступну команду curl:

curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -

Після імпортування ключа додайте репозиторій APT з використанням наступної команди:

echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

Оновіть індекс менеджера пакетів APT

sudo apt update

та встановіть Yarn за допомогою наступних команд. Наступна команда також встановить Node.js під час встановлення Yarn.

sudo apt install yarn

Якщо ви не хочете встановлювати Node.js автоматично за допомогою Yarn, скористайтеся наступною командою:

sudo apt install --no-install-recommends yarn

Тепер перевірте встановлення та версію Yarn, використовуючи наступну команду:

yarn --version
1.17.3

Install NodeJS – Ubuntu 18.04

NodeSource – це компанія, орієнтована на забезпечення підтримки Node корпоративного рівня, і вони підтримують сховище, що містить останні версії Node.js.

Щоб встановити Node.js і npm з сховища NodeSource, виконайте такі дії:

1. Увімкніть сховище NodeSource наступною командою curl:

curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -

Наведена вище команда додасть ключ підпису NodeSource до вашої системи, створить файл сховища apt source, встановить всі необхідні пакети та оновить кеш apt.

Поточна версія LTS Node.js є версією 10.x, Carbon. Якщо вам потрібно встановити версію 8.x, просто замініть setup_10.x на setup_8.x

2. Після додавання репозиторію NodeSource встановіть Node.js і npm, командою:

sudo apt install nodejs

3. Переконайтеся, що Node.js та npm успішно встановлені, надрукувавши їх версії

node --version
v10.16.0

npm --version
6.9.0