|
| 1 | +## How to host Node.js apps on Ubuntu |
| 2 | + |
| 3 | +### Step 1 - Installing Node.js & build essentials |
| 4 | +``` |
| 5 | +curl -fsSL https://deb.nodesource.com/setup_21.x | sudo -E bash - &&\ |
| 6 | +sudo apt-get install -y nodejs |
| 7 | +``` |
| 8 | +Now install build essentials |
| 9 | +``` |
| 10 | +sudo apt-get install build-essential |
| 11 | +``` |
| 12 | + |
| 13 | +### Step 2 - Create a sample Node.js app |
| 14 | +You can also use your own app if you want to host it. Otherwise if you are just trying out, you can use a sample app. |
| 15 | + |
| 16 | + |
| 17 | +### Step 3 - Install pm2 & launch your app |
| 18 | +Install pm2 package which is a process manager for Node.js applications |
| 19 | +``` |
| 20 | +sudo npm install -g pm2 |
| 21 | +``` |
| 22 | + |
| 23 | +Now launch your app using this command |
| 24 | +``` |
| 25 | +pm2 start index.js |
| 26 | +``` |
| 27 | + |
| 28 | +### Step 4 - Install nginx |
| 29 | +Nginx is a web server which we will be using as a proxy |
| 30 | +``` |
| 31 | +sudo apt install nginx |
| 32 | +``` |
| 33 | + |
| 34 | +Now edit the file at /etc/nginx/sites-available/default using following command |
| 35 | +``` |
| 36 | +sudo nano /etc/nginx/sites-available/default |
| 37 | +``` |
| 38 | + |
| 39 | +We want this file to look like this: |
| 40 | +``` |
| 41 | +. . . |
| 42 | + location / { |
| 43 | + proxy_pass http://localhost:3000; |
| 44 | + proxy_http_version 1.1; |
| 45 | + proxy_set_header Upgrade $http_upgrade; |
| 46 | + proxy_set_header Connection 'upgrade'; |
| 47 | + proxy_set_header Host $host; |
| 48 | + proxy_cache_bypass $http_upgrade; |
| 49 | + } |
| 50 | +} |
| 51 | +... |
| 52 | +``` |
| 53 | + |
| 54 | +### Step 5 - Test and restart nginx |
| 55 | +Test and restart nginx using following commands |
| 56 | +``` |
| 57 | +sudo nginx -t |
| 58 | +``` |
| 59 | +Now restart using: |
| 60 | +``` |
| 61 | +sudo systemctl restart nginx |
| 62 | +``` |
0 commit comments