Deploy Nest JS App With Postgres in VPS

Farhaz Alam
The Startup
Published in
5 min readNov 9, 2020

In this article, will show you how to deploy a REST API made using Nest JS along with Postgres in Ubuntu 20.04 LTS.

STEP 1 (SETUP POSTGRES)

Install Postgres by typing in the terminal:

$ sudo apt-get update
$ sudo apt-get install postgresql postgresql-contrib

Now that Postgres is installed in your system, you can switch to Postgres user by:

$ su - postgres

Now logged in as Postgres user, you can easily switch to the Postgres shell by typing

$ psql

You will see something like this:

root@testapi:~# su — postgrespostgres@testapi:~# psql..postgres=#

CREATE USER

Exit from the Postgres shell by typing ‘ \q ’. Don't change the user now. Now when logged in as Postgres user, type the below command to create a new user.

$ createuser --interactive --pwprompt

It will ask you for the name and password for the new user that you want to set. Then ask if you want to give Superuser Privileges to the user or not. It will look something like this.

postgres@testapi:~$ createuser --interactive --pwprompt
Enter name of role to add: admin
Enter password for new role:
Enter it again:
Shall the new role be a superuser? (y/n) y

Now let us create a database and assign the user to it by typing:

$ createdb -O admin jugaad

Here the name of the Database is jugaad and the user assigned to it is admin.

Accessing Postgres Outside VPS (OPTIONAL)

Now if you want to access your database from outside the VPS Server using PG Admin or any other tool, you can follow the below steps:

$ nano /etc/postgresql/12/main/postgresql.conf

In the above file, search for listen_addresses = ‘localhost’, uncomment it and change it to listen_addresses = ‘*’ then save and exit it. The output will look like:

...
listen_addresses = '*' # what IP address(es) to listen on;
...

Now again, open the below config file by typing:

$ nano /etc/postgresql/12/main/pg_hba.conf

Again run the above command and search for IPv4 local connections’ section and change the IP-address from 127.0.0.1/32 to 0.0.0.0/0

The final output will look like this:

...
# IPv4 local connections:
host all all 0.0.0.0/0 md5
...

Now after all that is complete, Exit from the Postgres user by typing ‘exit’.

Now allow the incoming connection on port 5432(Default Port of Postgres) then restart the Postgres Service.

$ sudo ufw allow 5432/tcp
$ sudo systemctl restart postgresql

After completing all the steps, you will be able to access your database outside the Server via PG Admin or any other tools that you need.

STEP 2(SETUP NODE)

Now the database configuration is done, all we have to do now is set up the Node JS. The below commands will install node, npm, pm2 and Nest JS(Obviously):

Remember to exit from the Postgres user(if you haven't) by typing exit.

$ curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
$ sudo apt-get install -y nodejs
$ sudo npm install pm2@latest -g
$ sudo npm i -g @nestjs/cli

Now I already have a Nest JS app that uses Postgres Database in my repo to use for this tutorial, you can obviously use your own as the procedure will be the same.

Assuming you cloned or copied your Folder in the home, navigate to the folder and create a .env file in the root of the folder for storing all the database credentials(assuming you don't want to compromise on it).

The .env file will store the credentials that will be used by the Nest JS when establishing a database connection.

For reference the contents of the .env file will look like this where the host refers to the localhost and the rest is self-explanatory:

DB_HOST=127.0.0.1
DB_PORT=5432
DB_USERNAME=admin
DB_PASSWORD=admin
DB_NAME=jugaad

Now install the project dependencies and build the nest js app by typing:

$ npm i
$ nest build

PM2 SETUP

Now all that we have to do is use the PM2 to run our Nest JS App:

$ pm2 start dist/main.js --name jugaadapi

The above command executes the app and the name of the process will be jugaadapi. You can see the log by using pm2 log.

If you didn't get any errors, then you are good to go.

Now make sure pm2 restarts after system restart by:

$ pm2 startup systemd
$ pm2 save

If you followed all the above steps correctly then your Nest JS app is running in the server. But wait, it's not a very realistic approach to access your API using IP addresses. So the only thing left is to Setup a domain or a Subdomain and connect to your API.

STEP 3(SETUP DOMAIN/SUBDOMAIN)

Install Nginx and configure firewall settings with the below command:

$ sudo apt-get install nginx
$ sudo ufw allow 'Nginx Full'
$ sudo ufw allow ssh
$ sudo ufw enable

Note: Point the IP of the server to ‘A’ record of your Domain Provider DNS Settings. In my case it will be the middle one from the below image

Now that Nginx is installed, let's make a server block to access our API:

$ sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/api.jugaadapp.me
$ sudo nano /etc/nginx/sites-available/api.jugaadapp.me

I will be using api.jugaadapp.me to access my API. Remember, you must own the domain in order to access it, or else it won't work.

Now in the editor, remove the default_server word in the server block, but the server name that you are going to access the URL in the server_name portion and lastly make some changes in the location block inside the server as below, the final File will look something like this.

server {
listen 80;
listen [::]:80;

root /var/www/html;
index index.html index.htm index.nginx-debian.html;

server_name api.jugaadapp.me;

location / {
proxy_pass http://localhost:3000;
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;
# try_files $uri $uri/ =404;
}
}

Now that your server block is ready, we will need to enable the block by typing:

$ sudo ln -s /etc/nginx/sites-available/api.jugaadapp.me /etc/nginx/sites-enabled/

Additional Step

$ sudo nano /etc/nginx/nginx.conf

Go to the above file and uncomment the Line server_names_hash_bucket_size 64;

Check for any syntax errors in the Nginx then restart the server:

$ sudo nginx -t
$ sudo systemctl restart nginx

Your NEST JS with Postgres Database is now successfully deployed in the desired URL in Ubuntu.

ENJOY!!

--

--