Setup Strapi Headless CMS on Ubuntu with Nginx

CitrusLeaf Presents- Strapi setup on Ubuntu with Nginx

In today’s rapidly expanding age of APIs, headless CMS are gaining immense popularity because of their flexibility and simple integration capabilities. Strapi is one such CMS that has become a go-to option for developers when building API based applications.

With its modern architecture and a user-friendly interface, Strapi allows developers to create and manage their APIs and content with ease. Strapi’s API-based approach also allows for easy integration with other third-party services and tools, making it a versatile choice for any type of project.

If you’re looking to create a website or web/mobile application using Strapi as the backend CMS, the first step would be to set up Strapi on a Linux server. While Strapi can be installed on various operating systems, Linux/Ubuntu is a popular choice due to its stability and reliability.

Additionally, using Nginx as the web server can provide a secure and scalable solution for serving your Strapi project.

In this article, we will walk you through the process of setting up a Strapi project on a Linux/Ubuntu server using Nginx as the web server (in reverse-proxy mode). We will also cover installing and setting up a PostgreSQL database server. 

Install Node.js and Yarn: 

Both Yarn and npm are package managers for Node.js that allow developers to manage dependencies in their Node Js projects. While you could use NPM as your package manager of choice, using Yarn has more advantages and it is our preferred choice.

Yarn’s main advantage is its speed, which is achieved through parallel installation and caching of downloaded packages for future installations. This is especially beneficial for large projects. It also has a simpler and more consistent command line interface compared to NPM. Its commands are easy to remember and use, with fewer syntax and option variations.

Additionally, Yarn has some features that are not available in NPM, such as the ability to install packages from multiple registries and the ability to lock dependencies to specific versions. 

While both Yarn and NPM are useful tools for managing dependencies, Yarn’s speed, predictability, and ease of use make it a popular choice among developers

Install the packages using the below commands:

$ sudo apt-get update
$ sudo apt-get install nodejs yarn

Setup PostgreSQL

Postgres, also known as PostgreSQL, is a widely-used open-source relational database management system. Its stability, reliability, and advanced features have made it a popular choice for all kinds of systems which require a relational database.

Postgres is highly scalable, easily handles complex and large databases without sacrificing performance or stability. Its robust feature set includes advanced indexing, support for geospatial and JSON data types, and SQL extensions, enabling developers to create complex queries and customize their databases. 

Postgres is very flexible, allowing developers to create customized extensions and functions as per their specific needs. Additionally, Postgres is known for its security and reliability, offering SSL encryption, user authentication, and row-level security features, with a community-driven development approach ensuring constant updates and improvements. 

Use the following commands to install PostgreSQL :

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

Switch to the postgres user and create a new PostgreSQL user

$ sudo su - postgres
$ psql

Then, enter the following commands in the PostgreSQL command prompt:

CREATE USER strapi WITH PASSWORD 'your-password';
ALTER ROLE strapi SET client_encoding TO 'utf8';
ALTER ROLE strapi SET default_transaction_isolation TO 'read committed';
ALTER ROLE strapi SET timezone TO 'UTC';
CREATE DATABASE myproject OWNER strapi;

Install Strapi globally

Strapi is a popular open-source headless CMS that provides developers with a platform to build APIs quickly and with ease. It is highly flexible and scalable, allowing developers to have full control over their APIs without any restrictions.

Strapi’s most amazing feature is the ability to generate standard CRUD REST and GraphQL APIs for the entities that you create in it. It also gives you all the filter and sort options right in the generated APIs, so you do not have to worry about building them from scratch.

Of course, you can create as many custom APIs as you want. Strapi is extremely flexible that way.

Strapi is also known for its intuitive Admin dashboard and user-friendly interface, which simplifies the management of content and APIs. A few clicks, and you have your APIs ready, right from the Admin interface.

In addition, Strapi has a modular architecture that makes it highly extensible and enables seamless integration with other tools and services. You can create all sorts of customization like extensions and plugins to make it your own.

Before you install Strapi project, it’s advisable to first install the Strapi CLI and then use it to generate a Strapi project.

Command to install Strapi :

$ sudo yarn global add strapi@beta

Create a new Strapi Project and Install Dependencies

$ strapi new my-project
$ cd my-project
$ yarn install

Update the Strapi project configuration file to use PostgreSQL:

Update the config/database.js to use PostgreSQL:

module.exports = ({env}) => ({
  connection: {
    client: 'postgres',
    connection: {
      host: env('DATABASE_HOST', '127.0.0.1'),
      port: env.int('DATABASE_PORT', 5432),
      database: env('DATABASE_NAME', ''),
      user: env('DATABASE_USERNAME', 'postgres'),
      password: env('DATABASE_PASSWORD', ''),
      ssl: env.bool('DATABASE_SSL', false),
    },
  },
});

Create one .env file in your strapi project and add the following

DATABASE_PORT = 5432
DATABASE_NAME = myproject  // your db name
DATABASE_USERNAME = strapi //your username
DATABASE_PASSWORD = your-password 

Install and configure Nginx

Nginx is an open-source web server and reverse proxy server known for its exceptional performance, scalability, and ability to handle a large number of concurrent connections. Acting as a gateway between the client and server, Nginx receives and forwards client requests to the appropriate backend server for processing. This mode is called reverse-proxy mode. This enhances security, reliability, and performance by relieving backend servers of tasks like load balancing, SSL termination, and caching. 

The popularity of Nginx as a reverse proxy server is due to its lightweight, fast, and flexible nature. It supports a wide range of protocols, including HTTP, HTTPS, TCP, and UDP, and its robust feature set makes it easily configurable for different use cases. 

Moreover, the active community of developers contributing to its development and providing support to users has made Nginx one of the most widely used web and reverse proxy servers today.

You can install nginx in your system using the following commands:

You can install nginx in your system using the following commands:

$ sudo apt-get install nginx

Add the following configuration to the file (/etc/nginx/conf.d/sitename.conf):

server {
 server_name your-website-name.com

 # Strapi server
 location / {
   proxy_pass http://localhost:1337;
   proxy_set_header Access-Control-Allow-Origin *;
   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;
  }
 }

Test the Nginx configuration and restart the service

$ sudo nginx -t
$ sudo server restart nginx  or  sudo systemctl restart nginx

Start the strapi project with the command:

$ yarn run develop

Open your browser and navigate to http://your-domain.com to see your Strapi project running through Nginx.

Install and configure PM2

Unlike traditional runtimes like Java and PHP, you need a process manager for NodeJS apps to run them in the background. This makes sure that the Node process which is handling incoming requests is always running and can restart should there be any error.

PM2 is one of the most popular and most used process management tools for NodeJS. It has all kinds of options to manage a Nodejs application in the background. It is basically a daemon process which makes sure that the supported command (nodejs in our case) runs indefinitely, unless stopped.

Some of the features of PM2 are-

  • Behavior configuration
  • Source map support
  • Container Integration
  • Watch & Reload
  • Log management
  • Monitoring
  • Module System
  • Max memory reload

Install PM2 using Yarn or NPM-

Install PM2 process manager to run the Strapi app in the background:

$ sudo yarn global add pm2

However, managing your application with PM2 requires you to specify the start command each time you want to start it. This can become tedious, especially when managing multiple applications or needing to start an application several times.

To simplify this process, you can create an ecosystem.config.js file that contains configuration information for PM2 for a particular NodeJS app. This file allows you to specify the settings for each of your applications in a single location, which can make managing your applications much easier.

To create an ecosystem.config.js file, you can follow these steps:

  1. Open your project directory in a code editor.
  2. Create a new file called “ecosystem.config.js” in the root directory of your project.
  3. Inside the ecosystem.config.js file, add the following:
module.exports = {
  apps: [{
    name: ’yourAppName’,
    exec_mode: 'cluster',
    instances: 'max',
    script: 'yarn',
    args: 'develop',
  }],
};
  1. Replace “yourAppName” with the name of your application.
  2. Save the file and exit the code editor.

The code mentioned above instructs PM2 to launch your application using the “yarn” command with the “start” argument. Furthermore, the “watch: true” option enables PM2 to detect any changes made to the source code and automatically restart the application.

To start your application using the ecosystem.config.js file, simply run the following command in your project directory:

$ pm2 start ecosystem.config.js

Conclusion

In conclusion, setting up a Strapi project on Linux using Nginx and PM2 can provide a highly reliable and scalable solution for serving your backend API to the internet. 

By following the steps outlined in this article, you can easily install and configure Strapi on your Linux server, as well as configure Nginx to handle incoming requests and serve your Strapi project to the web. Additionally, using PM2 as a process manager can help ensure that your Strapi server stays online and responsive, even in the face of high traffic or unexpected errors. Whether you’re building a simple website or a complex web or mobile application, Strapi provides a versatile and reliable CMS solution that can help you manage your content with ease. So, if you’re ready to get started with Strapi, follow these steps and get your project up and running on a secure and stable server today.

If you are looking to deploy your Strapi project on a Windows server, you can find detailed instructions in one of our previous blog posts – “Deploying Strapi on Windows Server without using Process Managers” and get started with deploying your project on a Windows server.


If you are looking for someone to help you with Strapi development or if you are hiring Strapi developers to create a entire backend for next application, contact us at hello@citrusleaf.in