How can I deploy Node Js back-end and React Js front-end on server? - node.js

I have created a back-end using Node Express which is running on port 5000. And my front-end using React Js which is running on port 3000. And both of them are in different folders in root directory.
I want to upload both of these and deploy on digital ocean Server. I am new to this department process. How can I deploy both of these on server and run by one command, please

Here is one way of doing it (using node server to serve as an API for React website served by Apache server).
You can leave nodejs running on port 5000 (on the remote server) but make sure that you are not using localhost but 0.0.0.0.
ie. app.listen(5000, "0.0.0.0");
Now, you should be able to communicate with the node server via public IP/DNS name on that port ie. myPublicIpOrDNSname:5000. (assuming that you have installed nodejs as well as npm => be careful about version, apt-get install nodejs, by default, will fetch an older version)
If you need newer version of nodejs then you can fetch it by following these steps (you can replace that setup_8.x part with your preferred version).
cd ~
curl -sL https://deb.nodesource.com/setup_8.x -o nodesource_setup.sh
sudo bash nodesource_setup.sh
sudo apt-get install nodejs
Use Apache2 server to serve your static (React, css, ...) files (you don't need to run create-react-app server).
sudo apt-get update
sudo apt-get install apache2
Build your React project using npm run build and then place the files that were created inside of /build folder (in the React folder) to /var/www/html (on the remote server). Note that you need to place there files and folders from /build folder, not the /build folder itself.
Now you should be able to see your react website running when you type the myPublicIpOrDNSname address (assuming that Apache is running sudo systemctl start apache2).
For Apache to work correctly (if you are using front-end routing - ie. react-router-dom), you need to go to /etc/apache2/sites-enabled/000-default.conf and place this configuration
<Directory "/var/www/html">
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
</Directory>
under <VirtualHost ...> section in that file. (Apache does't know about your React routes. This will make it push every request that it doesn't know how to handle to the root and leave React handle the routing)
Then you need to make sure that RewriteEngine is running (otherwise you will get an error when restarting Apache server).
sudo a2enmod rewrite
Finally, restart Apache server
sudo /etc/init.d/apache2 restart
Now, it should work.
Note that you need to modify your ajax calls in your React with the new public IP/DNS.

If your front-end is create react app, you can do npm run build, and serve static assets in nodejs via nodejs in the same server. It will serve the minified chunks.
app.use(express.static(path.join(__dirname, '../client/build')));

You can server side render your react app from your Node.js/Express, I think currently your are using webpack to render your react app on port 3000. If you can upload your code to take a look it will be easier to help

Related

Reverse proxy to serve local reactjs application on a static url with virtualmin

I've got a locally running reactJS app that I'd like to run as a subdomain on a domain hosted on virtualmin, so that the app can be hosted locally but seen publicly.
ngrok.io allows you to serve a locally running reactjs application (or a lot of other things) through a publicly visible subdomain.
(My intention is to answer my own question, because when I searched, I ran into a lot of dead ends. I tried to use as many keywords as I used while searching out the answer.)
On Virtualmin, click on 'Create Virtual Server'
For the domain name, use "subdomain.x.com"
Enabled Features: Setup DNS Zone (if necessary), apache website enabled, and apache ssl website enabled.
Click on Server Configuration -> Edit Proxy Website
Set "Proxy enabled?" to "Yes". Proxy to url: http://localhost:12809/
Run your reactjs app on your localhost. We're assuming it is running on port 8301.
On your localhost, establish an ssh tunnel to your server; do:
ssh -N -T -R 12809:localhost:8301 user#x.com
reload "subdomain.x.com" and your locally running reactjs app will be seen publicly there.
If you need websockets enabled, make sure to add this to your apache configuration file at Services->Configure Website->Edit Directives.
RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]
RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC]
RewriteRule .* ws://localhost:12809%{REQUEST_URI} [P]
in the RewriteEngine On section
edit: this was an unnecessary step when i originally wrote this, but i'm leaving it here to show how you can route through yet another server if you want/need:
) Download 'caddy' to your virtualmin user home directory: https://caddyserver.com/download
) Then run a reverse proxy on caddy from the port that will connect to your localhost (9000, in this case) to the port that is served from subdomain.x.com:
`./caddy reverse-proxy --from :12809 --to 127.0.0.1:9000`
) in this case you'd run your ssh on your localhost like 9000:localhost:8301

host public node js website on amazon AWS LightSail without Bitnami

I have an amazon AWS LightSail instance and have installed Node js downloaded from nodejs.org. Now the setup is complete and I am able to launch my nodejs webpage inside LightSail instance using "http://localhost but when I try to do it using the lightsail public IP from any other laptop, it not getting accessible (getting web error as "This site can’t be reached").
I have set the node js to listen to port 80 which is open by default.
A lot of materials shows that bitnami as a way to do it but can't I use normal node js installation to make the website public. Appreciate any guidance on this
Bitnami Engineer here,
You can configure your Nodejs app to use the port 3000 and then configure Apache to ProxyPass the requests to that port. This way you will be able to access your app using http and https. Does that sound good? You will need to run these commands:
Create the folders
sudo mkdir -p /opt/bitnami/apps/myapp
sudo mkdir /opt/bitnami/apps/myapp/conf
sudo mkdir /opt/bitnami/apps/myapp/htdocs
Create a /opt/bitnami/apps/myapp/conf/httpd-prefix.conf file with this content
Include "/opt/bitnami/apps/myapp/conf/httpd-app.conf"
Add this content to the /opt/bitnami/apps/myapp/conf/httpd-app.conf file
ProxyPass / http://127.0.0.1:3000/
ProxyPassReverse / http://127.0.0.1:3000/
Add this line to the /opt/bitnami/apache2/conf/bitnami/bitnami-apps-prefix.conf file
Include "/opt/bitnami/apps/myapp/conf/httpd-prefix.conf"
Restart Apache
sudo /opt/bitnami/ctlscript.sh restart apache
You have more information in our documentation
https://docs.bitnami.com/aws/infrastructure/nodejs/administration/create-custom-application-nodejs/

Run node.js on cpanel hosting server

It is a simple node.js code.
var http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type' : 'text/plain'});
res.end('Hello World!');
}).listen(8080);
I uploaded it on cpanel hosting server and installed node.js and run it.
If a server is normal server I can check script result by accessing 'http://{serverip}:8080'. But on cpanel is hosting domain and sub domain and every domain is matched by every sites. Even http://{serverip} is not valid url.
How can I access my node.js result?
Kindly teach me.
Thanks.
bingbing.
Install/Setup NodeJS with CPanel
1. Log in to your account using SSH (if it is not enabled for your account, contact the support team).
2. Download Node.js
wget https://nodejs.org/dist/latest/node-v10.0.0-linux-arm64.tar.xz
3. Extract the Node.js files
tar xvf node-v10.0.0-linux-arm64.tar.xz
4.Now rename the folder to "nodejs". To do this, type the following command
mv node-v10.0.0-linux nodejs
5. Now to install the node and npm binaries, type the following commands:
mkdir ~/bin <br> cp nodejs/bin/node ~/bin
cd ~/bin
ln -s
../nodejs/lib/node_modules/npm/bin/npm-cli.js npm
6. Node.js and npm are installed on your account. To verify this, type the following commands
node --version
npm --version
The ~/bin directory is in your path by default, which means you can run node and npm from any directory in your account.
7. Start Node.js Application
nohup node my_app.js &
8. Stop the Application
pkill node
9. Integrating a Node.js application with the web server(optional)
Depending on the type of Node.js application you are running, you may want to be able to access it using a web browser. To do this, you need to select an unused port for the Node.js application to listen on, and then define server rewrite rules that redirect visitors to the application.
In a text editor, add the following lines to the .htaccess file in the/home/username/public_html directory, where username represents your account username:
RewriteEngine On
RewriteRule ^$ http://127.0.0.1:XXXXX/ [P,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ http://127.0.0.1:XXXXX/$1 [P,L]
In both RewriteRule lines, replace XXXXX with the port on which your Node.js application listens.
To run a Node.js application on a managed server, you must select an unused port, and the port number must be between 49152 and 65535(inclusive).
Save the changes to the .htaccess file, and then exit the text editor. Visitors to your website are redirected to the Node.js application listening on the specified port.
If your application fails to start, the port you chose may already be in use. Check the application log for error codes like EADDRINUSE that indicate the port is in use. If it is, select a different port number, update your application’s configuration and the .htaccess file, and then try again.
cPanel typically runs Apache or another web server that is shared among all the cPanel/unix accounts. The web server listens on port 80. Depending on the domain name in the requested URL, the web server uses "Virtual Hosting" to figure out which cPanel/unix account should process the request, i.e. in which home directory to find the files to serve and scripts to run. If the URL only contains an IP address, cPanel has to default to one of cPanel accounts.
Ordinarily, without root access, a job run by a cPanel account cannot listen on port 80. Indeed, the available ports might be quite restrictive. If 8080 doesn't work, you might try 60000. To access a running node.js server, you'll need to have the port number it's listening on. Since that is the only job listening on that port on that server, you should be able to point your browser to the domain name of any of the cPanel accounts or even the IP address of the server, adding the port number to the URL. But, it's typical to use the domain name for the cPanel account running the node.js job, e.g. http://cPanelDomainName.com:60000/ .
Of course port 80 is the default for web services, and relatively few users are familiar with optional port numbers in URLs. To make things easier for users, you can use Apache to "reverse proxy" requests on port 80 to the port that the node.js process is listening on. This can be done using Apache's RewriteRule directive in a configuration or .htaccess file. This reverse proxying of requests arguably has other benefits as well, e.g. Apache may be a more secure, reliable and manageable front-end for facing the public Internet.
Unfortunately, this setup for node.js is not endorsed by all web hosting companies. One hosting company that supports it, even on its inexpensive shared hosting offerings, is A2Hosting.com. They also have a clearly written description of the setup process in their Knowledge Base.
Finally, it's worth noting that the developers of cPanel are working on built-in node.js support. "If all of the stars align we might see this land as soon as version 68," i.e. perhaps early 2018.
References
Apache Virtual Hosting -
http://httpd.apache.org/docs/2.4/vhosts/
Apache RewriteRule Directive - http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html
A2Hosting.com Knowledge Base Article on Configuring Node.js - https://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-managed-hosting-accounts
cPanel Feature Request Thread for node.js Support - https://features.cpanel.net/topic/nodejs-hosting
Related StackOverflow Questions
How to host a Node.Js application in shared hosting
Why node.js can't run on shared hosting?
Yes it's possible, but it has few dependencies which may or may not be supported by either your cpanel hosting provider or the plan you opt in for.
Below steps that I'm mentioning is just for a demo purpose. If you are a student or just want to play with it you can try it out. I'm not a security expert so from security point of view how good it is I really don't know.
So with that being said let's see how I configured it. I have hostinger cpanel hosting subscription and following are the steps:
Enable SSH ACCESS
Connect to shared machine via ssh
Check your linux distro and download & setup node js
In my case following are the commands for that:
Downloading node & extracting it using curl
curl https://nodejs.org/dist/v12.18.3/node-v12.18.3-linux-x64.tar.gz |tar xz
This will download & extract node & create a directory. You can confirm that using ls command as shown in the image below.
At this point you can check the versions as shown below
as you can see for the node command it's okay but for the npm command we have modify it as follows
./node-v12.18.3-linux-x64/bin/node ./node-v12.18.3-linux-x64/lib/node_modules/npm/bin/npm-cli.js --version
Further we can create alias to make life little easier
check the below images for that:
I tried using bashrc/bash_profile but somehow it didn't work .
And that's all node server running on a shared cpanel machine.
Now I wanted to have an express js based rest api support in this case. The problem with that is it will be locally hosted on the port I'll give. Check the below example:
var express=require('express')
var app=express()
app.get('/', function (req, res) {
res.send('hosting node js base express api using php & shared hosting a great way to start yjtools')
})
console.log("listening yjtools node server on port 49876...")
app.listen(49876)
The problem here is even though it will execute I'll not be able to access it over the network. This is because we only get fixed predefined ports (like 80,21,3306 etc.) which are allowed/open on the shared cpanel machine. Due to this the express app I hosted will only available locally on 49876 port.
Let's see what do we have:
An express js based app hosted locally on cpanel machine.
Php based hosted Apache server available over http/https.
So we can make use of php with redirect rule set and curl to bridge the gap.
Following are the changes I did to make it work:
In .htaccess file add a redirect rule, say domain/api is what I want my rest api path to be.
RewriteRule api/(.*)$ api/api.php?request=$1 [QSA,NC,L]
In the api/api.php file (this is the path I choose you can choose any path)
<?php
echo "Hello ".$_REQUEST['username'];
echo '<hr>';
$curl = curl_init('http://127.0.0.1:49976/');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//Get the full response
$resp = curl_exec($curl);
if($resp === false) {
//If couldn't connect, try increasing usleep
echo 'Error: ' . curl_error($curl);
} else {
//Split response headers and body
list($head, $body) = explode("\r\n\r\n", $resp, 2);
$headarr = explode("\n", $head);
//Print headers
foreach($headarr as $headval) {
header($headval);
}
//Print body
echo $body;
}
//Close connection
curl_close($curl);
?>
And on the ssh prompt just run the app.js file
node api/app.js
Below are the images for this working in action:
Here is the similar thing which I referred for my program, so we can also make this node call via php itself.
Now I have express based rest api support , angular app hosted and mysql for database everything on cpanel.
You can use any domain pointed to that cPanel server and instead of accessing http://server-ip:8080 try accessing http://domain.tld:8080. By default cPanel does not bind on port 8080. Be sure to check if there is any firewall on the server. If it is, then allow incoming connections on tcp port 8080. Depending on your WHM server configuration, it should also work with http://server-ip:8080
cPanel Version 80 has nodejs 10.x support: https://documentation.cpanel.net/display/80Docs/80+Release+Notes#id-80ReleaseNotes-InstallanduseNode.jsapplications
Install and use Node.js applications
You can now install and use Node.js applications on your server. To
use Node.js, install the ea-nodejs10 module in the Additional Packages
section of WHM's EasyApache 4 interface (WHM >> Home >> Software >>
EasyApache 4).
You can register Node.js applications in cPanel's Application Manager
interface (cPanel >> Home >> Software >> Application Manager). For
more information, read our Guide to Node.js Installations
documentation.
For Application Manager to be enabled: https://documentation.cpanel.net/display/80Docs/Application+Manager
Your hosting provider must enable the Application Manager feature in
WHM's Feature Manager interface (WHM >> Home >> Packages >> Feature
Manager).
Your hosting provider must install the following Apache modules:
The ea-ruby24-mod_passengermodule. Note: This module disables Apache's
mod_userdir module.
The ea-apache24-mod_env module. Note: This module allows you to add
environment variables when you register your application. For more
information about environment variables, read the Environment
Variables section below.
The ea-nodejs10 module if you want to register a Node.js™ application.
You can see how application manager looks like in this Youtube video:
https://www.youtube.com/watch?v=ATxMYzLbRco
anyone who wants to know how to deploy node js app to Cpanel this is a good source for him, this explains thoroughly how to deploy node js app to Cpanel please check this

How to run multi Laravel projects on XAMPP or Wamp

I have one laravel project in Xampp and I set my localhost to localhost/laravel/public
and now I want to start another laravel project and now I dont know what should I do.
I created a laravel project in another folder named : blog
but laravel router doesnt work anyway
You need to use virtual hosts (if you're using Apache) to map different hostnames to different directories on the same server.
https://httpd.apache.org/docs/current/vhosts/examples.html
If you're using Nginx, you would use "server blocks"
I assume that you are not in the production environment, and trying locally to develop. In this case, you can run the built-in laravel php server using the artisan command.
Normal usage.
//run this command inside your folder, in this case inside blog folder.
php artisan serv
This will start the server on localhost:8000. However, the above command also accept a parameter called port. Run the above command in other laravel project folder with a different port.
php artisan serv --port=9000
Which will run the server in 9000 port and can be tested using localhost:9000.
If you are using for production purpose, try apache virtual host or nginx virtual host based on your server.

Ionic Desktop Testing

Is there any advantage in testing the ionic app on a web browser using the the ionic serve command vs just running a local apache server and browsing the www folder (e.g. http://localhost/www/#/app/home). I checked the serve.js file in the npm module and apparently all it does is listening for a tcp connection on a default port using nodejs modules.
There are a few advantages, but you are certainly able to use a local apache server as well.
ionic serve benefits
It runs with the ability to have live reload, meaning if you save a file in your editor the app will auto-refresh in your browser. You can disable by with the -r flag on the command.
It can open a browser when you start up, which can be nice or annoying. You can disable with the -b flag on the command.
It sets up a local server for you, regardless if your files are in the apache www directory. It lets you store the files anywhere in your system.
Apache benefits
You can setup .htaccess rules to rewrite urls to properly support html5mode in Angular. I don't do this on mobile apps since the urls are not available in apps.
Runs on port 80. You don't have to worry about ports or remembering what port to use.
Its up to you really, but I use ionic serve. You can also use cordova serve which does the same as ionic serve without live reload and browser open, and runs on localhost:8000.

Resources