From a877a00934b57a89b0f90eae54b6b0bdd0e100ca Mon Sep 17 00:00:00 2001 From: Alexandre Bodin Date: Fri, 10 Apr 2020 15:47:47 +0200 Subject: [PATCH] Update docuemntation Signed-off-by: Alexandre Bodin --- docs/3.0.0-alpha.x/guides/deployment.md | 927 +++++++++++++----- .../3.0.0-beta.x/admin-panel/customization.md | 96 +- docs/3.0.0-beta.x/admin-panel/deploy.md | 74 +- docs/3.0.0-beta.x/cli/CLI.md | 10 - docs/3.0.0-beta.x/concepts/configurations.md | 256 ++--- docs/3.0.0-beta.x/concepts/hooks.md | 18 +- docs/3.0.0-beta.x/concepts/middlewares.md | 8 +- docs/3.0.0-beta.x/concepts/models.md | 2 +- docs/3.0.0-beta.x/concepts/webhooks.md | 52 +- docs/3.0.0-beta.x/guides/client.md | 86 +- docs/3.0.0-beta.x/guides/databases.md | 36 +- docs/3.0.0-beta.x/guides/error-catching.md | 34 +- .../guides/scheduled-publication.md | 13 +- .../installation/digitalocean-one-click.md | 17 +- .../3.0.0-beta.x/plugins/users-permissions.md | 2 +- 15 files changed, 999 insertions(+), 632 deletions(-) diff --git a/docs/3.0.0-alpha.x/guides/deployment.md b/docs/3.0.0-alpha.x/guides/deployment.md index 3e6946c88c..c61de2f14a 100644 --- a/docs/3.0.0-alpha.x/guides/deployment.md +++ b/docs/3.0.0-alpha.x/guides/deployment.md @@ -2,93 +2,138 @@ Strapi gives you many possible deployment options for your project or application. Strapi can be deployed on traditional hosting servers or services such as Heroku, AWS, Azure and others. The following documentation covers how to develop locally with Strapi and deploy Strapi with various hosting options. -(Deploying **databases** along with Strapi is covered in the [Databases Guide](/3.0.0-alpha.x/guides/databases.html).) - -**Table of contents:** - -- [Configuration](#configuration) -- [Amazon AWS](#amazon-aws) -- [Digital Ocean](#digital-ocean) -- [Heroku](#heroku) -- [Docker](#docker) - ---- +::: tip +Deploying **databases** along with Strapi is covered in the [Databases Guide](../guides/databases.md). +::: ## Configuration -#### #1 - Configure +#### 1. Configure -Update the `production` settings with the IP and domain name where the project will be running. +Update the `production` settings with the IP or domain name where the project will be running. **Path —** `./config/environments/production/server.json`. ```js { - "host": "domain.io", // IP or domain - "port": 1337, - "autoReload": { - "enabled": false - }, - "admin": { - "path": "/dashboard" // We highly recommend to change the default `/admin` path for security reasons. - } + "host": "domain.io",// IP or domain or 0.0.0.0 + "port": 1337 } ``` In case your database is not running on the same server, make sure that the environment of your production database (`./config/environments/production/database.json`) is set properly. -If you are passing a number of configuration item values via environment variables which is always encouraged for production environment to keep application stateless, checkout the section for [Dynamic Configuration](../configurations/configurations.md#dynamic-configurations). Here is a hint on how to do it for production, for the configuration mentioned above: +If you are passing a number of configuration item values via environment variables, which is always encouraged for production environment, read the section for [Dynamic Configuration](../concepts/configurations.md#dynamic-configurations). Here is an example: **Path —** `./config/environments/production/server.json`. ```js { - "host": "${process.env.APP_HOST || '127.0.0.1'}" - "port": "${process.env.NODE_PORT || 1337}", - "autoReload": { - "enabled": false - }, - "admin": { - "path": "/dashboard" // We highly recommend to change the default `/admin` path for security reasons. - } + "host": "${process.env.APP_HOST || '0.0.0.0'}", + "port": "${process.env.NODE_PORT || 1337}" } ``` -**⚠️ If you changed the path to access to the administration, the step #2 is required.** +#### 2. Launch the server -#### #2 - Setup (optional) +Before running your server in production you need to build your admin panel for production -Run this following command to install the dependencies and build the project with your custom configurations. +:::: tabs + +::: tab yarn ```bash -cd /path/to/the/project -npm run setup +NODE_ENV=production yarn build ``` -::: tip -To display the build logs use the --debug option `npm run setup --debug`. ::: -#### #3 - Launch the server +::: tab npm + +```bash +NODE_ENV=production npm run build +``` + +::: + +::: tab Windows + +```bash +npm install cross-env +``` + +Then in your `package.json` scripts section: + +```bash +"production": "cross-env NODE_ENV=production npm run build" +``` + +::: + +:::: Run the server with the `production` settings. +:::: tabs + +::: tab yarn + +```bash +NODE_ENV=production yarn start +``` + +::: + +::: tab npm + ```bash NODE_ENV=production npm start ``` -::: warning -We highly recommend to use [pm2](https://github.com/Unitech/pm2/) to manage your process. ::: +::: tab Windows + +```bash +npm install cross-env +``` + +Then in your `package.json` scripts section: + +```bash +"production": "cross-env NODE_ENV=production npm start" +``` + +::: + +:::: + +::: warning +We highly recommend using [pm2](https://github.com/Unitech/pm2/) to manage your process. +::: + +If you need a server.js file to be able to run `node server.js` instead of `npm run start` then create a `./server.js` file as follows: + +```js +const strapi = require('strapi'); + +strapi(/* {...} */).start(); +``` + ### Advanced configurations -If you want to host the administration on another server than the API, [please take a look at this dedicated section](../advanced/customize-admin.md#deployment). +If you want to host the administration on another server than the API, [please take a look at this dedicated section](../admin-panel/deploy.md). + +## Docker + +In this section, you will not find a specific guide to deploy your app with [Docker](https://www.docker.com/). + +We recently updated the [strapi/strapi-docker](https://github.com/strapi/strapi-docker) GitHub repository that contains all informations needed to user Strapi with Docker. ## Amazon AWS -This is a step-by-step guide for deploying a Strapi project to [Amazon AWS EC2](https://aws.amazon.com/ec2/). This guide will connect to an [Amazon AWS RDS](https://aws.amazon.com/rds/) for managing and hosting the database. Optionally, this guide will show you how to connect host and serve images on [Amazon AWS S3](https://aws.amazon.com/s3/). Prior to starting this guide, you should have created a [Strapi project](/3.0.0-alpha.x/getting-started/quick-start.html), to use for deploying on AWS. +This is a step-by-step guide for deploying a Strapi project to [Amazon AWS EC2](https://aws.amazon.com/ec2/). This guide will connect to an [Amazon AWS RDS](https://aws.amazon.com/rds/) for managing and hosting the database. Optionally, this guide will show you how to connect host and serve images on [Amazon AWS S3](https://aws.amazon.com/s3/). Prior to starting this guide, you should have created a [Strapi project](../getting-started/quick-start.md), to use for deploying on AWS. ### Amazon AWS Install Requirement and creating an IAM non-root user @@ -96,12 +141,12 @@ This is a step-by-step guide for deploying a Strapi project to [Amazon AWS EC2]( Best practices for using **AWS Amazon** services state to not use your root account user and to use instead the [IAM (AWS Identity and Access Management) service](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html). Your root user is therefore only used for a very few [select tasks](https://docs.aws.amazon.com/general/latest/gr/aws_tasks-that-require-root.html). For example, for **billing**, you create an **Administrator user and Group** for such things. And other, more routine tasks are done with a **regular IAM User**. -1. Follow these instructions for [creating your Administrator IAM Admin User and Group](https://docs.aws.amazon.com/IAM/latest/UserGuide/getting-started_create-admin-group.html). +#### 1. Follow these instructions for [creating your Administrator IAM Admin User and Group](https://docs.aws.amazon.com/IAM/latest/UserGuide/getting-started_create-admin-group.html) - Login as **root**. - Create **Administrator** role. -2. Next, create a **regular user** for the creation and management of your Strapi project. +#### 2. Next, create a **regular user** for the creation and management of your Strapi project - Copy your **IAM Users sign-in link** found here: [IAM Console](https://console.aws.amazon.com/iam/home) and then log out of your **root user** and log in to your **administrator** user you just created. - Return to the IAM Console by `searching for IAM` and clicking or going here: [IAM Console](https://console.aws.amazon.com/iam/home). @@ -132,7 +177,7 @@ Best practices for using **AWS Amazon** services state to not use your root acco - **OPTIONAL:** Add these credentials to your \*Password manager\*\*. - Click on the `AWS Management Console Access sign-in link`. This will log you out of `Administrator`. -3. `Log into` your **AWS Management Console** as your `regular user`. +#### 3. `Log into` your **AWS Management Console** as your `regular user` You may now proceed to the next steps. @@ -145,15 +190,21 @@ You may now proceed to the next steps. Amazon calls a virtual private server, a **virtual server** or **Amazon EC2 instance**. To use this service you will `Launch Instance`. In this section, you will **establish IAM credentials**, **launch a new instance** and **set-up primary security rules**. -1. From your **AWS Management Console** and as your **_regular_** user: +#### 1. From your **AWS Management Console** and as your **_regular_** user -- `Find Services`, seach for `ec2` and click on `EC2, Virtual Servers in the Cloud` +- `Find Services`, search for `ec2` and click on `EC2, Virtual Servers in the Cloud` -2. **Select Appropriate Region**. In the top menu, near your IAM Account User name, select, from the dropdown, the most appropriate region to host your Strapi project. For example, `US East (N.Virginia)` or `Asia Pacific (Hong Kong)`. You will want to remember this region for configuring other services on AWS and serving these services from the same region. -3. Click on the blue `Launch Instance` button. +#### 2. **Select Appropriate Region** + +In the top menu, near your IAM Account User name, select, from the dropdown, the most appropriate region to host your Strapi project. For example, `US East (N.Virginia)` or `Asia Pacific (Hong Kong)`. You will want to remember this region for configuring other services on AWS and serving these services from the same region. + +#### 3. Click on the blue `Launch Instance` button - `Select` **Ubuntu Server 18.04 LTS (HVM), SSD Volume Type** -- Ensure `General purpose` + `t2.micro` is `checked`. +- Ensure `General purpose` + `t2.small` is `checked`. + ::: tip + `t2.small` is the smallest instance type in which Strapi runs. `t2.nano` and `t2.micro` **DO NOT** work. At the moment, deploying the Strapi Admin interface requires more than 1g of RAM. Therefore, **t2.small** or larger instance is needed. + ::: - Click the grey `Next: Configure Instance Details` and `Next: Add Storage` - In the **Step 4: Add Storage** verify the `General Purpose SSD (gb2)`, then click `Next: Add tags`. - In the **Step 5: Add Tags**, add tags to suit your project or leave blank, then click `Next: Configure Security Group`. @@ -167,12 +218,17 @@ Amazon calls a virtual private server, a **virtual server** or **Amazon EC2 inst - **Type:** `HTTP`, **Protocol:** `TCP`, **Port Range** `80`, **Source:** `0.0.0.0/0, ::/0` - **Type:** `HTTPS`, **Protocol:** `TCP`, **Port Range** `443`, **Source:** `0.0.0.0/0, ::/0` - **Type:** `Custom TCP Rule`, **Protocol:** `TCP`, **Port Range** `1337`, **Source:** `0.0.0.0/0` **Description:** `Strapi for Testing Port` - (These rules are basic configuration and security rules. You may want to tighten and limit these rules based on your own project and organizational policies. **Note:** After setting up your Nginx rules and domain name with the proper aliases, you will need to delete the rule regarding port 1337 as this is for testing and setting up the project - **not for production**.) + These rules are basic configuration and security rules. You may want to tighten and limit these rules based on your own project and organizational policies. + ::: tip + After setting up your Nginx rules and domain name with the proper aliases, you will need to delete the rule regarding port 1337 as this is for testing and setting up the project - **not for production**. + ::: - Click the blue `Review and Launch` button. - Review the details, in the **Step 7: Review Instance Launch**, then click the blue `Launch` button. Now, you need to **select an existing key pair** or **create a new key pair**. To create a new key pair, do the following: - Select the dropdown option `Create a new key pair`. - Name your the key pair name, e.g. `ec2-strapi-key-pair` - - **IMPORTANT** Download the **private key file** (.pem file). This file is needed, so note where it was downloaded. + ::: warning + Download the **private key file** (.pem file). This file is needed, so note where it was downloaded. + ::: - After downloading the file, click the blue `Launch Instances` button. Your instance is now running. Continue to the next steps. @@ -181,12 +237,22 @@ Your instance is now running. Continue to the next steps. Amazon calls their database hosting services **RDS**. Multiple database options exist and are available. In this guide, **PostgreSQL** is used as the example, and the steps are similar for each of the other database that are supported by Strapi. (**MySQL**, **MondoDB**, **PostgreSQL**, **MariaDB**, **SQLite**). You will set-up an **RDS instance** to host your `postgresql` database. -**NOTE:** **Amazon RDS** does **NOT** have a completely free evaluation tier. After finishing this guide, if you are only testing, please remember to [delete the database](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_DeleteInstance.html). Otherwise, you will incur charges. +::: tip +**Amazon RDS** does **NOT** have a completely free evaluation tier. After finishing this guide, if you are only testing, please remember to [delete the database](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_DeleteInstance.html). Otherwise, you will incur charges. +::: -1. Navigate to the `AWS RDS Service`. In the top menu, click on `Services` and do a search for `rds`, click on `RDS, Managed Relational Database Service`. -2. In the top menu bar, select the region that is the same as the EC2 instance, e.g. `EU (Paris)` or `US East (N. Virgina)`. +#### 1. Navigate to the `AWS RDS Service` -3. Click the orange `Create database` button. Follow these steps to complete installation of a `PostgreSQL` database: +In the top menu, click on `Services` and do a search for `rds`, click on `RDS, Managed Relational Database Service`. + +#### 2. Select your region + +In the top menu bar, select the region that is the same as the EC2 instance, e.g. `EU (Paris)` or `US East (N. Virgina)`. + +#### 3. Create the database + +Click the orange `Create database` button. +Follow these steps to complete installation of a `PostgreSQL` database: - **Engine Options:** Click on `PostgreSQL`, version **PostgreSQL 10.x-R1** - **Templates:** Click on `Free Tier`. @@ -207,8 +273,13 @@ After a few minutes, you may refresh your page and see that your database has be Amazon calls cloud storage services **S3**. You create a **bucket**, which holds the files, images, folders, etc... which then can be accessed and served by your application. This guide will show you have to use **Amazon S3** to host the images for your project. -1. Navigate to the `Amazon S3`. In the top menu, click on `Services` and do a search for `s3`, click on `Scalable storage in the cloud`. -2. Click on the blue `Create bucket` button: +#### 1. Navigate to the `Amazon S3` + +In the top menu, click on `Services` and do a search for `s3`, click on `Scalable storage in the cloud`. + +#### 2. Create the bucket + +Click on the blue `Create bucket` button: - Give your bucket a unique name, under **Bucket name**, e.g. `my-project-name-images`. - Select the most appropriate region, under **Region**, e.g. `EU (Paris)` or `US East (N. Virgina)`. @@ -228,16 +299,14 @@ Amazon calls cloud storage services **S3**. You create a **bucket**, which holds You will set-up your EC2 server as a Node.js server. Including basic configuration and Git. -**Requirements:** You will need your **EC2** ip address: - In the `AWS Console`, navigate to the `AWS EC2`. In the top menu, click on `Services` and do a search for `ec2`, click on `Virtual Servers in the cloud`. - Click on `1 Running Instance` and note the `IPv4 Public OP` address. E.g. `34.182.83.134`. -**On your local computer:** - -1. You downloaded, in a previous step, your `User` .pem file. e.g. `ec2-strapi-key-pair.pem`. This needs to be included in each attempt to `SSH` into your `EC2 server`. Move your `.pem` file to `~/.ssh/`, follow these steps: +#### 1. Setup the `.pem` file +- You downloaded, in a previous step, your `User` .pem file. e.g. `ec2-strapi-key-pair.pem`. This needs to be included in each attempt to `SSH` into your `EC2 server`. Move your `.pem` file to `~/.ssh/`, follow these steps: - On your local machine, navigate to the folder that contains your .pem file. e.g. `downloads` - Move the .pem file to `~/.ssh/` and set file permissions: `Path:./path-to/.pem-file/` @@ -247,9 +316,11 @@ mv ec2-strapi-key-pair.pem ~/.ssh/ chmod 400 ~/.ssh/ec2-strapi-key-pair.pem ``` -2. Log in to your server as the default `ubuntu` user: +#### 2. Log in to your server as the default `ubuntu` user: -**NOTE:** In the future, each time you log into your `EC2` server, you will need to add the path to the .pem file, e.g. `ssh -i ~/.ssh/ec2-strapi-key-pair.pem ubuntu@12.123.123.11`. +::: tip +In the future, each time you log into your `EC2` server, you will need to add the path to the .pem file, e.g. `ssh -i ~/.ssh/ec2-strapi-key-pair.pem ubuntu@12.123.123.11`. +::: ```bash ssh -i ~/.ssh/ec2-strapi-key-pair.pem ubuntu@12.123.123.11 @@ -265,7 +336,7 @@ ubuntu@ip-12.123.123.11:~$ ``` -3. Install **Node.js** with **npm**: +#### 3. Install **Node.js** with **npm**: Strapi currently supports `Node.js v10.x.x`. The following steps will install Node.js onto your EC2 server. @@ -280,7 +351,9 @@ node -v && npm -v The last command `node -v && npm -v` should output two versions numbers, eg. `v10.x.x, 6.x.x`. -4. Create and change npm's default directory. The following steps are based on [how to resolve access permissions from npmjs.com](https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally): +#### 4. Create and change npm's default directory. + +The following steps are based on [how to resolve access permissions from npmjs.com](https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally): - Create a `.npm-global` directory and set the path to this directory for `node_modules` @@ -317,15 +390,21 @@ A convenient way to maintain your Strapi application and update it during and af The next step is to configure Git on your server. -1. Check to see if `Git` is installed, if you see a `git version 2.x.x` then you do have `Git` installed. Check with the following command: +#### 1. Check to see if `Git` is installed + +If you see a `git version 2.x.x` then you do have `Git` installed. Check with the following command: ```bash git --version ``` -2. **OPTIONAL:** Install Git. **NOTE:** Only do if _not installed_, as above. Please follow these directions on [how to install Git on Ubuntu 18.04](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git). +#### 2. **OPTIONAL:** Install Git. -3. Configure the global **username** and **email** settings: [Setting up Git - Your Identity](https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup) +::: tip +Only do if _not installed_, as above. Please follow these directions on [how to install Git on Ubuntu 18.04](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git). +::: + +#### 3. Configure the global **username** and **email** settings: [Setting up Git - Your Identity](https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup) After installing and configuring Git on your EC2 instance. Please continue to the next step. @@ -333,18 +412,23 @@ After installing and configuring Git on your EC2 instance. Please continue to th These instructions assume that you have already created a **Strapi** project, and have it in a **GitHub** repository. -**On your local computer:** +You will need to update the `database.json` file to configure Strapi to connect to the `RDS` database. And you will need to install an npm package called `pg` locally on your development server. +::: tip +The `pg` package install is only necessary if you are using **PostgresSQL** as your database. +::: -You will need to update the `database.json` file to configure Strapi to connect to the `RDS` database. And you will need to install an npm package called `pg` locally on your development server. **NOTE:** The `pg` package install is only necessary if you are using **PostgresSQL** as your database. +#### 1. Install `pg` in your Strapi project. -1. Install `pg` in your Strapi project. On your development machine, navigate to your Strapi project root directory: - `Path: ./my-project/` +On your development machine, navigate to your Strapi project root directory: +`Path: ./my-project/` ```bash npm install pg ``` -2. Edit the `database.json` file. Copy/paste the following: +#### 2. Edit the `database.json` file. + +Copy/paste the following: `Path: ./my-project/config/environments/production/database.json`: @@ -353,7 +437,7 @@ npm install pg "defaultConnection": "default", "connections": { "default": { - "connector": "strapi-hook-bookshelf", + "connector": "bookshelf", "settings": { "client": "postgres", "host": "${process.env.DATABASE_HOST || '127.0.0.1'}", @@ -370,13 +454,17 @@ npm install pg } ``` -3. Install the **Strapi Provider Upload AWS S3 Plugin**: `Path: ./my-project/`. This plugin will allow configurations for each active environment. **NOTE:** You can only update the settings for _production_ when your Strapi project is actually in production. +#### 3. Install the **Strapi Provider Upload AWS S3 Plugin**: + +`Path: ./my-project/`. + +This plugin will allow configurations for each active environment. ```bash -npm install strapi-provider-upload-aws-s3@alpha +npm install strapi-provider-upload-aws-s3@beta ``` -4. Push your local changes to your project's GitHub repository. +#### 4. Push your local changes to your project's GitHub repository. ```bash git add . @@ -384,11 +472,11 @@ git commit -m 'installed pg, aws-S3 provider plugin and updated the production/d git push ``` -5. Deploy from GitHub +#### 5. Deploy from GitHub You will next deploy your Strapi project to your EC2 instance by **cloning it from GitHub**. -From your terminal, logged into your EC2 instance as the `ubuntu` user: +From your terminal and logged into your EC2 instance as the `ubuntu` user: ```bash cd ~ @@ -402,11 +490,12 @@ Next, navigate to the `my-project` folder, the root for Strapi. You will need to ```bash cd ./my-project/ npm install +NODE_ENV=production npm run build ``` Next, you need to install **PM2 Runtime** and configure the `ecosystem.config.js` file -5. Install **PM2 Runtime** +#### 6. Install **PM2 Runtime** [PM2 Runtime](https://pm2.io/doc/en/runtime/overview/?utm_source=pm2&utm_medium=website&utm_campaign=rebranding) allows you to keep your Strapi project alive and to reload it without downtime. @@ -416,7 +505,7 @@ Ensure you are logged in as a **non-root** user. You will install **PM2** global npm install pm2@latest -g ``` -Now, you will need to configure an `ecosystem.config.js` file. This file will set `env` variables that connect Strapi to your database. It will also be used to restart your project whenever any changes are made to files within the Strapi file system itself (such as when an update arrived from Github).You can read more about this file [here](https://pm2.io/doc/en/runtime/guide/development-tools/). +Now, you will need to configure an `ecosystem.config.js` file. This file will set `env` variables that connect Strapi to your database. It will also be used to restart your project whenever any changes are made to files within the Strapi file system itself (such as when an update arrived from Github). You can read more about this file [here](https://pm2.io/doc/en/runtime/guide/development-tools/). - You will need to open your `nano` editor and then `copy/paste` the following: @@ -430,19 +519,22 @@ sudo nano ecosystem.config.js ```js module.exports = { - apps : [{ - name: 'strapi', - cwd: '/home/ubuntu/path-to/your-strapi-root-folder' - script: 'server.js', - env: { - NODE_ENV: 'production', - DATABASE_HOST: 'your-unique-url.rds.amazonaws.com', // database Endpoint under 'Connectivity & Security' tab - DATABASE_PORT: '5432', - DATABASE_NAME: 'strapi', // DB name under 'Configuration' tab - DATABASE_USERNAME: 'postgres', // default username - DATABASE_PASSWORD: 'Password', + apps: [ + { + name: 'your-app-name', + cwd: '/home/ubuntu/my-strapi-project/my-project', + script: 'npm', + args: 'start', + env: { + NODE_ENV: 'production', + DATABASE_HOST: 'your-unique-url.rds.amazonaws.com', // database Endpoint under 'Connectivity & Security' tab + DATABASE_PORT: '5432', + DATABASE_NAME: 'strapi', // DB name under 'Configuration' tab + DATABASE_USERNAME: 'postgres', // default username + DATABASE_PASSWORD: 'Password', + }, }, - }], + ], }; ``` @@ -453,11 +545,19 @@ cd ~ pm2 start ecosystem.config.js ``` -Your Strapi project should now be available on `http://your-ip-address:1337/`. **NOTE:** Earlier, `Port 1337` was allowed access for **testing and setup** purposes. After setting up **NGINX**, the **Port 1337** needs to have access **denied**. +Your Strapi project should now be available on `http://your-ip-address:1337/`. -6. Configure **PM2 Runtime** to launch project on system startup. +::: tip +Earlier, `Port 1337` was allowed access for **testing and setup** purposes. After setting up **NGINX**, the **Port 1337** needs to have access **denied**. +::: -Follow the steps below to have your app launch on system startup. (**NOTE:** These steps are based on the [PM2 Runtime Startup Hook Guide](https://pm2.io/doc/en/runtime/guide/startup-hook/).) +#### 7. Configure **PM2 Runtime** to launch project on system startup. + +Follow the steps below to have your app launch on system startup. + +::: tip +These steps are based on the [PM2 Runtime Startup Hook Guide](https://pm2.io/doc/en/runtime/guide/startup-hook/). +::: - Generate and configure a startup script to launch PM2, it will generate a Startup Script to copy/paste, do so: @@ -506,23 +606,23 @@ pm2 save The next steps involve configuring Strapi to connect to the AWS S3 bucket. -1. Locate your `IPv4 Public IP`: +#### 1. Locate your `IPv4 Public IP`: - Login as your regular user to your `EC2 Dashboard` - Click on `1 Running Instances`. - Below, in the **Description** tab, locate your **IPv4 Public IP** -2. Next, create your **Administrator** user, and login to Strapi: +#### 2. Next, create your **Administrator** user, and login to Strapi: - Go to `http://your-ip-address:1337/` - Complete the registration form. - Click `Ready to Start` -3. Configure the plugin with your bucket credentials: +#### 3. Configure the plugin with your bucket credentials: - From the left-hand menu, click `Plugins` and then the `cog` wheel located to the right of `Files Upload`. - From the dropdown, under **Providers**, select `Amazon Web Service S3` and enter the configuration details: - **Note:** You can find the **Access API Token** and **Secret Access Token** in the **configuration.csv** file you downloaded earlier or if you saved them to your password manager. + You can find the **Access API Token** and **Secret Access Token** in the **configuration.csv** file you downloaded earlier or if you saved them to your password manager. - **Access API Token**: This is your _Access Key ID_ - **Secret Access Token**: This is your _Secret Access Key_ Navigate back to your **Amazon S3 Dashboard**: @@ -559,9 +659,9 @@ cd NodeWebHooks sudo nano webhook.js ``` -- In the `nano` editor, copy/paste the following script, but make sure to replace `your_secret_key` and `repo` with the values that correspond to your project, then save and exit. **NOTE:** Earlier in this guide, there is a optional [recommended step](#the-ecosystem-config-js-file) to create an `ecosystem.config.js` file to manage your application restarting function. Below, use the correct version of the command as seen in the comments. +- In the `nano` editor, copy/paste the following script, but make sure to replace `your_secret_key` and `repo` with the values that correspond to your project, then save and exit. -(This script creates a variable called `PM2_CMD` which is used after pulling from GitHub to update your project. The script first changes to the home directory and then runs the variable `PM2_CMD` as `pm2 restart strapi`. If the project uses the `ecosystem.config.js` keep your `ecosystem.config.js` as the point of starting your application and use the alternative below. **PLEASE SEE COMMENTS IN THE CODE**.) +(This script creates a variable called `PM2_CMD` which is used after pulling from GitHub to update your project. The script first changes to the home directory and then runs the variable `PM2_CMD` as `pm2 restart strapi`. The project uses the `ecosystem.config.js` as the point of starting your application.) ```js var secret = 'your_secret_key'; // Your secret key from Settings in GitHub @@ -571,10 +671,7 @@ const http = require('http'); const crypto = require('crypto'); const exec = require('child_process').exec; -// Use this command if you DID NOT create the ecosystem.config.js file -const PM2_CMD = 'pm2 restart strapi'; -// Use this command if you DID create the ecosystem.config.js file and comment out/delete the above line. -// const PM2_CMD = 'cd ~ && pm2 startOrRestart ecosystem.config.js'; +const PM2_CMD = 'cd ~ && pm2 startOrRestart ecosystem.config.js'; http .createServer(function(req, res) { @@ -587,17 +684,14 @@ http .digest('hex'); if (req.headers['x-hub-signature'] == sig) { - exec( - `cd ${repo} && git pull && ${PM2_CMD}`, - (error, stdout, stderr) => { - if (error) { - console.error(`exec error: ${error}`); - return; - } - console.log(`stdout: ${stdout}`); - console.log(`stderr: ${stderr}`); + exec(`cd ${repo} && git pull && ${PM2_CMD}`, (error, stdout, stderr) => { + if (error) { + console.error(`exec error: ${error}`); + return; } - ); + console.log(`stdout: ${stdout}`); + console.log(`stderr: ${stderr}`); + }); } }); @@ -610,7 +704,7 @@ http - Within your **AWS EC2** dashboard: - In the left hand menu, click on `Security Groups`, - Select with the checkbox, the correct `Group Name`, e.g. `strapi`, - - At the bottom of the screen, , in the **Inbound** tab, click `Edit`, and then `Add Rule`: + - At the bottom of the screen, in the **Inbound** tab, click `Edit`, and then `Add Rule`: - Type: `Custom TCP` - Protocol: `TCP` - Port Range: `8080` @@ -636,7 +730,11 @@ echo $PATH sudo nano /etc/systemd/system/webhook.service ``` -- In the `nano` editor, copy/paste the following script, but make sure to replace `your-name` **in two places** with `Ubuntu`, and the `path from above` then save and exit (You must **delete the #comments**): +- In the `nano` editor, copy/paste the following script, but make sure to replace `ubuntu` **in two places** if you changed the default `ubuntu` user, and `paste the $PATH` from above. + +::: warning +**DELETE THE #COMMENTS BEFORE SAVING**, then save and exit. +::: ```bash [Unit] @@ -646,8 +744,8 @@ After=network.target [Service] Environment=PATH=/PASTE-PATH_HERE #path from echo $PATH (as above) Type=simple -User=your-name #replace your-name -ExecStart=/usr/bin/nodejs /home/your-name/NodeWebHooks/webhook.js #replace your-name +User=ubuntu #replace with your name, if changed from default ubuntu user +ExecStart=/usr/bin/nodejs /home/ubuntu/NodeWebHooks/webhook.js #replace with your name, if changed from default ubuntu user Restart=on-failure [Install] @@ -672,7 +770,9 @@ sudo systemctl status webhook ### Further steps to take - You can **add a domain name** or **use a subdomain name** for your Strapi project, you will need to [install NGINX](https://docs.nginx.com/nginx/admin-guide/installing-nginx/installing-nginx-open-source/) and [configure it](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/nodejs-platform-proxy.html). - - **NOTE:** After setting up **NGINX**, for security purposes, you need to disable port access on `Port 1337`. You may do this easily from your **EC2 Dashboard**. In `Security Groups` (lefthand menu), click the checkbox of the group, eg. `strapi`, and below in the `inbound` tab, click `Edit`, and delete the rule for `Port Range` : `1337` by click the `x`. + ::: tip + After setting up **NGINX**, for security purposes, you need to disable port access on `Port 1337`. You may do this easily from your **EC2 Dashboard**. In `Security Groups` (lefthand menu), click the checkbox of the group, eg. `strapi`, and below in the `inbound` tab, click `Edit`, and delete the rule for `Port Range` : `1337` by click the `x`. + ::: - To **install SSL**, you will need to [install and run Certbot by Let's Encrypt](https://certbot.eff.org/docs/using.html). - Set-up [Nginx with HTTP/2 Support](https://www.digitalocean.com/community/tutorials/how-to-set-up-nginx-with-http-2-support-on-ubuntu-18-04) for Ubuntu 18.04. @@ -681,7 +781,7 @@ Your `Strapi` project has been installed on an **AWS EC2 instance** using **Ubun ## Digital Ocean -This is a step-by-step guide for deploying a Strapi project to [Digital Ocean](https://www.digitalocean.com/). Databases can be on a [Digital Ocean Droplet](https://www.digitalocean.com/docs/droplets/) or hosted externally as a service. Prior to starting this guide, you should have created a [Strapi project](/3.0.0-alpha.x/getting-started/quick-start.html). +This is a step-by-step guide for deploying a Strapi project to [Digital Ocean](https://www.digitalocean.com/). Databases can be on a [Digital Ocean Droplet](https://www.digitalocean.com/docs/droplets/) or hosted externally as a service. Prior to starting this guide, you should have created a [Strapi project](../getting-started/quick-start.md). ### Digital Ocean Install Requirements @@ -691,15 +791,24 @@ This is a step-by-step guide for deploying a Strapi project to [Digital Ocean](h Digital Ocean calls a virtual private server, a [Droplet](https://www.digitalocean.com/docs/droplets/). You need to create a new `Droplet` to host your Strapi project. -1. Log in to your [Digital Ocean account](https://cloud.digitalocean.com/login). -2. `Create a Droplet` by clicking on `New Droplet`. Choose these options: +#### 1. Log in to your [Digital Ocean account](https://cloud.digitalocean.com/login). + +#### 2. `Create a Droplet` by clicking on `New Droplet`. + +Choose these options: - Ubuntu 18.04 x64 - STARTER `Standard` -- Choose an appropriate pricing plan. For example, pricing: `$5/mo` _(Scroll to the left)_ +- Choose an appropriate pricing plan. For example, pricing: `$10/mo` _(Scroll to the left)_ + ::: tip + The \$5/mo plan is currently unsupported as Strapi will not build with 1G of RAM. At the moment, deploying the Strapi Admin interface requires more than 1g of RAM. Therefore, a minimum standard Droplet of **\$10/mo** or larger instance is needed. + ::: - Choose a `datacenter` region nearest your audience, for example, `New York`. - **OPTIONAL:** Select additional options, for example, `[x] IPv6`. -- Add your SSH key **NOTE:** We recommend you `add your SSH key` for better security. +- Add your SSH key + ::: tip + We recommend you `add your SSH key` for better security. + ::: - In your terminal, use `pbcopy < ~/.ssh/id_rsa.pub` to copy your existing SSH public key, on your development computer, to the clipboard. - Click on `New SSH Key` and paste in your `SSH Key`. `Name` this SSH key and then `Save`. (Additional instructions on creating and using SSH Keys can be found [here](https://www.digitalocean.com/docs/droplets/how-to/add-ssh-keys/create-with-openssh/).) @@ -714,15 +823,21 @@ These next steps will help you to _set up a production server_ and _set up a non Follow the official [Digital Ocean docs for initial server set-up using Ubuntu 18.04](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-18-04). These docs will have you complete the following actions: -1. [Logging and set up root user access to your server with SSH](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-18-04#step-1-%E2%80%94-logging-in-as-root). -2. [Creating a new user](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-18-04#step-2-%E2%80%94-creating-a-new-user). -3. [Granting Administrative Privileges to the new user](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-18-04#step-3-%E2%80%94-granting-administrative-privileges). -4. [Setting up a basic firewall](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-18-04#step-4-%E2%80%94-setting-up-a-basic-firewall). -5. [Giving your regular user access to the server](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-18-04#step-5-%E2%80%94-enabling-external-access-for-your-regular-user) **with SSH key authentication**. +#### 1. [Logging and set up root user access to your server with SSH](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-18-04#step-1-%E2%80%94-logging-in-as-root). + +#### 2. [Creating a new user](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-18-04#step-2-%E2%80%94-creating-a-new-user). + +#### 3. [Granting Administrative Privileges to the new user](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-18-04#step-3-%E2%80%94-granting-administrative-privileges). + +#### 4. [Setting up a basic firewall](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-18-04#step-4-%E2%80%94-setting-up-a-basic-firewall). + +#### 5. [Giving your regular user access to the server](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-18-04#step-5-%E2%80%94-enabling-external-access-for-your-regular-user) **with SSH key authentication**. Next, install `Node.js`: -6. You will install `Node.js` using the instructions in section **Install Node using a PPA** from the official [Digital Ocean docs for installing a production ready Node.js server](https://www.digitalocean.com/community/tutorials/how-to-install-node-js-on-ubuntu-18-04#installing-using-a-ppa). +#### 6. You will install `Node.js`. + +Use the instructions in section **Install Node using a PPA** from the official [Digital Ocean docs for installing a production ready Node.js server](https://www.digitalocean.com/community/tutorials/how-to-install-node-js-on-ubuntu-18-04#installing-using-a-ppa). After completing the steps to **install Node.js, NPM and the "build-essential package"**, you will manually change npm's default directory. The following steps are based on [how to resolve access permissions from npmjs.com](https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally): @@ -761,15 +876,21 @@ A convenient way to maintain your Strapi application and update it during and af The next step is to configure Git on your server. -1. Check to see if `Git` is installed, if you see a `git version 2.x.x` then you do have `Git` installed. Check with the following command: +#### 1. Check to see if `Git` is installed + +If you see a `git version 2.x.x` then you do have `Git` installed. Check with the following command: ```bash git --version ``` -2. **OPTIONAL:** Install Git. **NOTE:** Only do this step if _not installed_, as above. Please follow these directions on [how to install Git on Ubuntu 18.04](https://www.digitalocean.com/community/tutorials/how-to-install-git-on-ubuntu-18-04). +#### 2. **OPTIONAL:** Install Git. -3. Complete the global **username** and **email** settings: [Setting up Git](https://www.digitalocean.com/community/tutorials/how-to-install-git-on-ubuntu-18-04#setting-up-git) +:::note +Only do this step if _not installed_, as above. Please follow these directions on [how to install Git on Ubuntu 18.04](https://www.digitalocean.com/community/tutorials/how-to-install-git-on-ubuntu-18-04). +::: + +#### 3. Complete the global **username** and **email** settings: [Setting up Git](https://www.digitalocean.com/community/tutorials/how-to-install-git-on-ubuntu-18-04#setting-up-git) After installing and configuring Git on your Droplet. Please continue to the next step, [installing a database](#install-the-database-for-your-project). @@ -779,7 +900,7 @@ Digital Ocean has excellent documentation regarding the installation and use of :::: tabs -::: tab "PostgreSQL" +::: tab PostgreSQL 1. [Install PostgresSQL on Ubuntu 18.04](https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-18-04)(Through **Step 4** - Creating a New Database). @@ -800,7 +921,7 @@ postgres=# \q exit ``` -- **Optional:** If in **Development**, your Strapi project uses **SQLite**, you will need to install a dependency package called `pg`: +- **OPTIONAL:** If in **Development**, your Strapi project is uses **SQLite**, you will need to install a dependency package called `pg`: - On your **Development** computer: @@ -810,7 +931,7 @@ exit npm install pg --save ``` - **Note:** The `pg` package is automatically installed locally if you choose `PostgreSQL` as the initial database choice when you first set-up Strapi. + The `pg` package is automatically installed locally if you choose `PostgreSQL` as the initial database choice when you first set-up Strapi. You will need the **database name**, **username** and **password** for later use, please note these down. @@ -828,7 +949,7 @@ In your code editor, you will need to edit a file called `database.json`. Replac "defaultConnection": "default", "connections": { "default": { - "connector": "strapi-hook-bookshelf", + "connector": "bookshelf", "settings": { "client": "postgres", "host": "${process.env.DATABASE_HOST || '127.0.0.1'}", @@ -863,7 +984,7 @@ Please continue to the next section, [Deploy from GitHub](#deploy-from-github). You will next deploy your Strapi project to your Droplet by `cloning it from GitHub`. -From your terminal and `logged in as your non-root user` to your Droplet: +From your terminal, `logged in as your non-root user` to your Droplet: ```bash cd ~ @@ -877,6 +998,7 @@ Next, navigate to the `my-project` folder, the root for Strapi. You will now nee ```bash cd ./my-project/ npm install +NODE_ENV=production npm run build ``` Strapi uses `Port: 1337` by default. You will need to configure your `ufw firewall` to allow access to this port, for testing and installation purposes. After you have installed and [configured NGINX](https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-18-04), you need to `sudo ufw deny 1337`, to close the port to outside traffic. @@ -890,7 +1012,7 @@ Command may disrupt existing ssh connections. Proceed with operation (y|n)? y Firewall is active and enabled on system startup ``` -Your Strapi project is now installed on your **Droplet**. You have a few more steps prior to being able to access Strapi and [create your first user](https://strapi.io/documentation/3.0.0-alpha.x/getting-started/quick-start.html#_3-create-an-admin-user). +Your Strapi project is now installed on your **Droplet**. You have a few more steps prior to being able to access Strapi and [create your first user](../getting-started/quick-start.md#_3-create-an-admin-user). You will next need to [install and configure PM2 Runtime](#install-and-configure-pm2-runtime). @@ -906,9 +1028,9 @@ npm install pm2@latest -g ### The ecosystem.config.js file -- You will need to configure an `ecosystem.config.js` file. This file will manage the **database connection variables** Strapi needs to connect to your database. The `ecosystem.config.js` will also be used by `pm2` to restart your project whenever any changes are made to files within the Strapi file system itself (such as when an update arrives from GitHub). You can read more about this file [here](https://pm2.io/doc/en/runtime/guide/development-tools/). +- You will need to configure an `ecosystem.config.js` file. This file will manage the **database connection variables** Strapi needs to connect to your database. The `ecosystem.config.js` will also be used by `pm2` to restart your project whenever any changes are made to files within the Strapi file system itself (such as when an update arrives from GitHub). You can read more about this file [here](https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page/). -- You will need to open your `nano` editor and then `copy/paste` the following: + - You will need to open your `nano` editor and then `copy/paste` the following: ```bash cd ~ @@ -919,22 +1041,24 @@ sudo nano ecosystem.config.js - Next, replace the boilerplate content in the file, with the following: ```js - module.exports = { - apps : [{ - name: 'strapi', - cwd: '/home/path-to/strapi-project-folder' - script: 'server.js', - env: { - NODE_ENV: 'production', - DATABASE_HOST: 'localhost', // database endpoint - DATABASE_PORT: '5432', - DATABASE_NAME: 'strapi', // DB name - DATABASE_USERNAME: 'your-name', // your username for psql - DATABASE_PASSWORD: 'password', // your password for psql +module.exports = { + apps: [ + { + name: 'strapi', + cwd: '/home/your-name/my-strapi-project/my-project', + script: 'npm', + args: 'start', + env: { + NODE_ENV: 'production', + DATABASE_HOST: 'localhost', // database endpoint + DATABASE_PORT: '5432', + DATABASE_NAME: 'strapi', // DB name + DATABASE_USERNAME: 'your-name', // your username for psql + DATABASE_PASSWORD: 'password', // your password for psql + }, }, - }], + ], }; - ``` Use the following command to start `pm2`: @@ -946,9 +1070,17 @@ pm2 start ecosystem.config.js `pm2` is now set-up to use an `ecosystem.config.js` to manage restarting your application upon changes. This is a recommended best practice. -**OPTIONAL:** You may see your project and set-up your first administrator user, by [creating an admin user](https://strapi.io/documentation/3.0.0-beta.x/getting-started/quick-start.html#_3-create-an-admin-user). **NOTE:** Earlier, `Port 1337` was allowed access for **testing and setup** purposes. After setting up **NGINX**, the **Port 1337** needs to have access **denied**. +**OPTIONAL:** You may see your project and set-up your first administrator user, by [creating an admin user](../getting-started/quick-start.md#_3-create-an-admin-user). -Follow the steps below to have your app launch on system startup. (**NOTE:** These steps are modified from the Digital Ocean [documentation for setting up PM2](https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-18-04#step-3-%E2%80%94-installing-pm2).) +::: tip +Earlier, `Port 1337` was allowed access for **testing and setup** purposes. After setting up **NGINX**, the **Port 1337** needs to have access **denied**. +::: + +Follow the steps below to have your app launch on system startup. + +::: tip +These steps are modified from the Digital Ocean [documentation for setting up PM2](https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-18-04#step-3-%E2%80%94-installing-pm2). +::: - Generate and configure a startup script to launch PM2, it will generate a Startup Script to copy/paste, do so: @@ -958,7 +1090,7 @@ $ pm2 startup systemd [PM2] Init System found: systemd [PM2] To setup the Startup Script, copy/paste the following command: -sudo env PATH=$PATH:/usr/bin /home/your-name/.npm-global/lib/node_modules/pm2/bin/pm2 startup systemd -u your-name --hp /home/your-name +sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u your-name --hp /home/your-name ``` - Copy/paste the generated command: @@ -1026,13 +1158,13 @@ sudo nano webhook.js ```js var secret = 'your_secret_key'; -var repo = '~/path-to/my-project/'; +var repo = '~/path-to-your-repo/'; const http = require('http'); const crypto = require('crypto'); const exec = require('child_process').exec; -const PM2_CMD = 'pm2 restart strapi'; +const PM2_CMD = 'cd ~ && pm2 startOrRestart ecosystem.config.js'; http .createServer(function(req, res) { @@ -1045,17 +1177,14 @@ http .digest('hex'); if (req.headers['x-hub-signature'] == sig) { - exec( - `cd ${repo} && git pull && ${PM2_CMD}`, - (error, stdout, stderr) => { - if (error) { - console.error(`exec error: ${error}`); - return; - } - console.log(`stdout: ${stdout}`); - console.log(`stderr: ${stderr}`); + exec(`cd ${repo} && git pull && ${PM2_CMD}`, (error, stdout, stderr) => { + if (error) { + console.error(`exec error: ${error}`); + return; } - ); + console.log(`stdout: ${stdout}`); + console.log(`stderr: ${stderr}`); + }); } }); @@ -1090,7 +1219,6 @@ echo $PATH ```bash cd ~ - sudo nano /etc/systemd/system/webhook.service ``` @@ -1102,7 +1230,7 @@ Description=Github webhook After=network.target [Service] -Environment=PATH=/PASTE-PATH_HERE +Environment=PATH=your_path Type=simple User=your-name ExecStart=/usr/bin/nodejs /home/your-name/NodeWebHooks/webhook.js @@ -1127,7 +1255,7 @@ sudo systemctl status webhook - You may test your **webhook** by following the instructions [here](https://www.digitalocean.com/community/tutorials/how-to-use-node-js-and-github-webhooks-to-keep-remote-projects-in-sync#step-4-testing-the-webhook). -### Further steps to take on your Droplet +### Further steps to take - You can **add a domain name** or **use a subdomain name** for your Strapi project, you will need to [install NGINX and configure it](https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-18-04). - Deny traffic to Port 1337. You have set-up a proxy using Nginx, you now need to block access by running the following command: @@ -1144,7 +1272,7 @@ Your `Strapi` project has been installed on a **Digital Ocean Droplet** using ** ## Heroku -This is a step-by-step guide for deploying a Strapi project to [Heroku](https://www.heroku.com/). Databases that work well with Strapi and Heroku are provided instructions on how to get started. +This is a step-by-step guide for deploying a Strapi project on [Heroku](https://www.heroku.com/). Databases that work well with Strapi and Heroku are provided instructions on how to get started. ### Heroku Install Requirements @@ -1153,7 +1281,7 @@ This is a step-by-step guide for deploying a Strapi project to [Heroku](https:// If you already have the Heroku CLI installed locally on your computer. Skip to [Login to Heroku](#_2-login-to-heroku-from-your-cli). -### 1. Heroku CLI Installation +#### 1. Heroku CLI Installation Download and install the `Heroku CLI` for your operating system: @@ -1170,7 +1298,7 @@ brew tap heroku/brew && brew install heroku ::: -::: tab "Ubuntu" +::: tab Ubuntu Run the following from your terminal: ```bash @@ -1179,16 +1307,16 @@ sudo snap install --classic heroku ::: -::: tab "Windows 10" +::: tab Windows Download the appropriate installer for your Windows installation: -[64-bit installer](https://cli-assets.heroku.com/heroku-x64.exe) -[32-bit installer](https://cli-assets.heroku.com/heroku-x86.exe) -::: +- [64-bit installer](https://cli-assets.heroku.com/heroku-x64.exe) +- [32-bit installer](https://cli-assets.heroku.com/heroku-x86.exe) + ::: :::: -### 2. Login to Heroku from your CLI +#### 2. Login to Heroku from your CLI Next, you need to login to Heroku from your computer. @@ -1198,25 +1326,47 @@ heroku login Follow the instructions and return to your command line. -### 3. Create a new project (or use an existing one) +#### 3. Create a new project (or use an existing one) -Create a [new Strapi project](/3.0.0-alpha.x/getting-started/quick-start.html) (if you want to deploy an existing project go to step 4). +Create a [new Strapi project](../getting-started/quick-start.md) (if you want to deploy an existing project go to step 4). ::: warning NOTE -If you plan to use **MongoDB** with your project, [refer to the create a Strapi project with MongoDB section of the documentation](/3.0.0-alpha.x/guides/databases.html#install-mongodb-locally) then, jump to step 4. +If you plan to use **MongoDB** with your project, [refer to the create a Strapi project with MongoDB section of the documentation](../guides/databases.md#install-mongodb-locally) then, jump to step 4. ::: `Path: ./` +:::: tabs + +::: tab yarn + +Use **yarn** to install the Strapi project (**recommended**). [Install yarn with these docs](https://yarnpkg.com/lang/en/docs/install/) + ```bash -strapi new my-project --quickstart +yarn create strapi-app my-project --quickstart ``` -**Note:** When you use `--quickstart` to create a Strapi project locally, a **SQLite database** is used which is not compatible with Heroku. Therefore, another database option [must be chosen](#_6-heroku-database-set-up). +::: -### 4. Update `.gitignore` +::: tab npx + +Use **npm/npx** to install the Strapi project + +```bash +npx create-strapi-app my-project --quickstart +``` + +::: + +:::: + +::: tip +When you use `--quickstart` to create a Strapi project locally, a **SQLite database** is used which is not compatible with Heroku. Therefore, another database option [must be chosen](#_6-heroku-database-set-up). +::: + +#### 4. Update `.gitignore` Add the following line at end of `.gitignore`: @@ -1228,7 +1378,7 @@ package-lock.json Even if it is usually recommended to version this file, it may create issues on Heroku. -### 5. Init a Git repository and commit your project +#### 5. Init a Git repository and commit your project Init the Git repository and commit your project. @@ -1238,10 +1388,10 @@ Init the Git repository and commit your project. cd my-project git init git add . -git commit -am "Initial Commit" +git commit -m "Initial Commit" ``` -### 6. Create a Heroku project +#### 6. Create a Heroku project Create a new Heroku project. @@ -1251,7 +1401,7 @@ Create a new Heroku project. heroku create ``` -(You can use `heroku create custom-project-name`, to have Heroku create a `custom-project-name.heroku.com` URL. Otherwise, Heroku will automatically generate a random project name (and URL) for you.) +You can use `heroku create custom-project-name`, to have Heroku create a `custom-project-name.heroku.com` URL. Otherwise, Heroku will automatically generate a random project name (and URL) for you. ::: warning NOTE If you have a Heroku project app already created. You would use the following step to initialize your local project folder: @@ -1266,19 +1416,19 @@ heroku git:remote -a your-heroku-app-name Your local development environment is now set-up and configured to work with Heroku. You have a new Strapi project and a new Heroku app ready to be configured to work with a database and with each other. -### 7. Heroku Database set-up +#### 7. Heroku Database set-up Below you will find database options when working with Heroku. Please choose the correct database (e.g. PostgreSQL, MongoDB, etc.) and follow those instructions. :::: tabs -::: tab "PostgreSQL" +::: tab PostgreSQL -#### Heroku Postgres +### Heroku Postgres Follow these steps to deploy your Strapi app to Heroku using **PostgreSQL**: -##### 1. Install the [Heroku Postgres addon](https://elements.heroku.com/addons/heroku-postgresql) for using Postgres. +#### 1. Install the [Heroku Postgres addon](https://elements.heroku.com/addons/heroku-postgresql) for using Postgres. To make things even easier, Heroku provides a powerful addon system. In this section, you are going to use the Heroku Postgres addon, which provides a free "Hobby Dev" plan. If you plan to deploy your app in production, it is highly recommended switching to a paid plan. @@ -1288,7 +1438,7 @@ To make things even easier, Heroku provides a powerful addon system. In this sec heroku addons:create heroku-postgresql:hobby-dev ``` -##### 2. Retrieve database credentials +#### 2. Retrieve database credentials The add-on automatically exposes the database credentials into a single environment variable accessible by your app. To retrieve it, type: @@ -1302,7 +1452,7 @@ This should print something like this: `DATABASE_URL: postgres://ebitxebvixeeqd: (This url is read like so: \*postgres:// **USERNAME** : **PASSWORD** @ **HOST** : **PORT** : **DATABASE_NAME\***) -##### 3. Set environment variables +#### 3. Set environment variables Strapi expects a variable for each database connection configuration (host, username, etc.). So, from the url above, you have to set several environment variables in the Heroku config: @@ -1314,9 +1464,9 @@ heroku config:set DATABASE_PORT=5432 heroku config:set DATABASE_NAME=d516fp1u21ph7b ``` -**Note:** Please replace these above values with your actual values. +Please replace these above values with your actual values. -##### 4. Update your database config file +#### 4. Update your database config file Replace the contents of `database.json` with the following: @@ -1327,7 +1477,7 @@ Replace the contents of `database.json` with the following: "defaultConnection": "default", "connections": { "default": { - "connector": "strapi-hook-bookshelf", + "connector": "bookshelf", "settings": { "client": "postgres", "host": "${process.env.DATABASE_HOST}", @@ -1343,7 +1493,7 @@ Replace the contents of `database.json` with the following: } ``` -##### 5. Install the `pg` node module +#### 5. Install the `pg` node module Unless you originally installed Strapi with PostgreSQL, you need to install the [pg](https://www.npmjs.com/package/pg) node module. @@ -1355,33 +1505,35 @@ npm install pg --save ::: -::: tab "MongoDB" +::: tab MongoDB -#### MongoDB Atlas +### MongoDB Atlas (Using Strapi and MongoDB requires different set-up and different configuration steps. You cannot use `--quickstart` to develop a `MongoDB` Strapi project.) Please follow these steps the **deploy a Strapi app with MongoDB on Heroku**. -You must have completed the [steps to use Strapi with MongoDB Atlas in production](/3.0.0-alpha.x/guides/databases.html#install-on-atlas-mongodb-atlas). +You must have completed the [steps to use Strapi with MongoDB Atlas](../guides/databases.md#install-on-atlas-mongodb-atlas) - through **4. Retrieve database credentials**. -##### 1. Set environment variables +#### 1. Set environment variables -When you [set-up your MongoDB Atlas database](/3.0.0-alpha.x/guides/databases.html#install-on-atlas-mongodb-atlas) you created and noted the five key/value pairs that correspond to your **MongoDB Atlas** database. These five keys are: `DATABASE_NAME`, `DATABASE_USERNAME`, `DATABASE_PASSWORD`, `DATABASE PORT`, and `DATABASE_HOST`. - -Strapi expects a variable for each database connection detail (host, username, etc.). So, from **MongoDB Atlas**, you have to set the environment variables in the Heroku config (for **DATABASE_HOST** you need to surround the URL with **""**, and set **DATABASE_PORT** to nothing): +When you [set-up your MongoDB Atlas database](../guides/databases.md#install-on-atlas-mongodb-atlas) you noted a connection string. Similar to this: ```bash -heroku config:set DATABASE_USERNAME=paulbocuse -heroku config:set DATABASE_PASSWORD=mySecretPassword -heroku config:set DATABASE_HOST="stapi-mongo-heroku-shard-00-00-fty6c.mongodb.net:27017,strapi-mongo-heroku-shard-00-01-fty6c.mongodb.net:27017,strapi-mongo-heroku-shard-00-02-fty6c.mongodb.net:27017/test?ssl=true&replicaSet=strapi-mongo-heroku-shard-0&authSource=admin&retryWrites=true" -heroku config:set DATABASE_PORT= -heroku config:set DATABASE_NAME=strapi-mongo-heroku +mongodb://paulbocuse:@strapidatabase-shard-00-00-fxxx6c.mongodb.net:27017,strapidatabase-shard-00-01-fxxxc.mongodb.net:27017,strapidatabase-shard-00-02-fxxxc.mongodb.net:27017/test?ssl=true&replicaSet=strapidatabase-shard-0&authSource=admin&retryWrites=true&w=majority + ``` -**Note:** Please replace these above values with your actual values. +So, from **MongoDB Atlas**, you have to set two environment variables in the Heroku config (for **DATABASE_URI** and **DATABASE_NAME**). Set the environment variables using the following commands: -##### 2. Update your database config file +```bash +heroku config:set DATABASE_URI="mongodb://paulbocuse:@strapidatabase-shard-00-00-fxxx6c.mongodb.net:27017,strapidatabase-shard-00-01-fxxxc.mongodb.net:27017,strapidatabase-shard-00-02-fxxxc.mongodb.net:27017/test?ssl=true&replicaSet=strapidatabase-shard-0&authSource=admin&retryWrites=true&w=majority" +heroku config:set DATABASE_NAME="my-database-name" +``` + +Please replace the `` and `my-database-name` values with the your actual values. + +#### 2. Update your database config file Replace the contents of `database.json` with the following: @@ -1392,14 +1544,10 @@ Replace the contents of `database.json` with the following: "defaultConnection": "default", "connections": { "default": { - "connector": "strapi-hook-mongoose", + "connector": "mongoose", "settings": { - "client": "mongo", - "host": "${process.env.DATABASE_HOST}", - "port": "${process.env.DATABASE_PORT}", - "database": "${process.env.DATABASE_NAME}", - "username": "${process.env.DATABASE_USERNAME}", - "password": "${process.env.DATABASE_PASSWORD}" + "uri": "${process.env.DATABASE_URI}", + "database": "${process.env.DATABASE_NAME}" }, "options": { "ssl": true @@ -1409,17 +1557,20 @@ Replace the contents of `database.json` with the following: } ``` +::: + :::: -### 8. Commit your changes +#### 8. Commit your changes `Path: ./my-project/` ```bash -git commit -am "Update database config" +git add . +git commit -m "Update database config" ``` -### 9. Deploy +#### 9. Deploy `Path: ./my-project/` @@ -1437,14 +1588,12 @@ heroku open If you see the Strapi Welcome page, you have correctly set-up, configured and deployed your Strapi project on Heroku. You will now need to set-up your `admin user` as the production database is brand-new (and empty). -You can now continue with the [Tutorial - Creating an Admin User](/3.0.0-alpha.x/getting-started/quick-start-tutorial.html#_3-create-an-admin-user), if you have any questions on how to proceed. +You can now continue with the [Tutorial - Creating an Admin User](../getting-started/quick-start-tutorial.md#_3-create-an-admin-user), if you have any questions on how to proceed. -::: warning NOTE +::: warning For security reasons, the Content Type Builder plugin is disabled in production. To update content structure, please make your changes locally and deploy again. ::: ---- - ### Project updates When Strapi is deployed to Heroku, Heroku sets the environment variable to `NODE_ENV=production`. In `production mode` Strapi disables the content-type builder (for security reasons). Additionally, if you wanted to change the default production mode in Heroku, it wouldn't work as the file system is temporary. Strapi writes files to the server when you update the content-types and these updates would disappear when Heroku restarts the server. @@ -1462,10 +1611,316 @@ git push heroku master heroku open ``` -## Docker +### File Uploads + +Like with project updates on Heroku, the file system doesn't support local uploading of files as they will be wiped when Heroku "Cycles" the dyno. This type of file system is called [ephemeral](https://devcenter.heroku.com/articles/dynos#ephemeral-filesystem), which means the file system only lasts until the dyno is restarted (with Heroku this happens any time you redeploy or during their regular restart which can happen every few hours or every day). + +Due to Heroku's filesystem you will need to use an upload provider such as AWS S3, Cloudinary, or Rackspace. You can view the documentation for installing providers [here](../plugins/upload.md#install-providers) and you can see a list of providers from both Strapi and the community on [npmjs.com](https://www.npmjs.com/search?q=strapi-provider-upload-&page=0&perPage=20). + +## Google App Engine + +In this guide we are going to: + +- Create a new Strapi project +- Configure PostgreSQL for the production enviroment +- Deploy the app to Google App Engine +- Add the [Google Cloud Storage file uploading plugin](https://github.com/Lith/strapi-provider-upload-google-cloud-storage) by [@Lith](https://github.com/Lith) + +### New Strapi project + +:::: tabs + +::: tab yarn + +Use **yarn** to install the Strapi project (**recommended**). [Install yarn with these docs](https://yarnpkg.com/lang/en/docs/install/) + +```bash +yarn create strapi-app my-project --quickstart +``` -::: tip -You can also deploy using [Docker](https://hub.docker.com/r/strapi/strapi) ::: -The method below describes regular deployment using the built-in mechanisms. +::: tab npx + +Use **npm/npx** to install the Strapi project + +```bash +npx create-strapi-app my-project --quickstart +``` + +::: + +:::: + +When the setup completes, register an admin user using the form which opens in the browser. This user will be only relevant in local development. + +The `sqlite` database is created at `.tmp/data.db`. + +Login, but don't add content types yet. Close the browser. Quit the running app. + +### Initial commit + +This may be a good point to commit the files in their initial state. + +```bash +cd my-project +git init +git add . +git commit -m first +``` + +### Install the Cloud SDK CLI tool + +[Cloud SDK: Command Line Interface](https://cloud.google.com/sdk/) + +### New App Engine project + +Create a new [App Engine](https://console.cloud.google.com/appengine/) project. + +Select the region, such as `europe-west`. + +- Language: Node JS +- Environment: Standard (or Flexible) + +(_A note on performance and cost_: the `Standard Environment` is sufficient for development, but it may not be for production. Review the resources your application will need to determine the cost. When you sign up for Google App Engine, it offers a certain amount of free credits which will not be billed.) + +Create the project. Take note of the instance identifier, which is in the form of `::`. + +Check if `gcloud` lists the project: + +```bash +gcloud projects list +``` + +Run `init` to authenticate the cli, and select current cloud project. + +```bash +gcloud init +``` + +### Create the database (PostgreSQL) + +Create the [Cloud SQL database](https://cloud.google.com/sql/docs/postgres/create-manage-databases) which the app is going to use. + +Take note of the user name (default is `postgres`) and password. + +The first database will be created with the name `postgres`. This cannot be deleted. + +Create another database, named `strapi` for example. It may be useful to delete and and re-create this while you are experimenting with the application setup. + +### Create app.yaml and .gcloudignore + +Create the `app.yaml` file in the project root. + +Add `app.yaml` to `.gitignore`. + +The instance identifier looks like `myapi-123456:europe-west1:myapi`. + +The `myapi-123456` part is the project identifier. (The number is automatically added to short project names). + +The following is an example config for `Standard Environment` or `Flexible Environment`. + +:::: tabs + +::: tab Standard Environment + +```yaml +runtime: nodejs10 + +instance_class: F2 + +env_variables: + HOST: '.appspot.com' + NODE_ENV: 'production' + DATABASE_NAME: 'strapi' + DATABASE_USERNAME: 'postgres' + DATABASE_PASSWORD: '' + INSTANCE_CONNECTION_NAME: '' + +beta_settings: + cloud_sql_instances: '' +``` + +::: + +::: tab Flexible Environment + +```yaml +runtime: nodejs10 + +env: flex + +env_variables: + HOST: '.appspot.com' + NODE_ENV: 'production' + DATABASE_NAME: 'strapi' + DATABASE_USERNAME: 'postgres' + DATABASE_PASSWORD: '' + INSTANCE_CONNECTION_NAME: '' + +beta_settings: + cloud_sql_instances: '' +``` + +::: + +:::: + +Create `.gcloudignore` in the project root, include `app.yaml` here as well. + +``` +app.yaml +.gcloudignore +.git +.gitignore +node_modules/ +#!include:.gitignore +``` + +In the case of Strapi, the admin UI will have to be re-built after every deploy, +and so we don't deploy local build artifacts, cache files and so on by including +the `.gitignore` entries. + +### Configure the database + +The `PostgreSQL` database will need the `pg` package. + +```bash +yarn add pg +``` + +[Google App Engine requires](https://cloud.google.com/sql/docs/postgres/connect-app-engine) to connect to the database using the unix socket path, not an IP and port. + +Edit `database.json`, and use the socket path as `host`. + +``` +config/environments/production/database.json +``` + +```json +{ + "defaultConnection": "default", + "connections": { + "default": { + "connector": "bookshelf", + "settings": { + "client": "postgres", + "host": "/cloudsql/${process.env.INSTANCE_CONNECTION_NAME}", + "database": "${process.env.DATABASE_NAME}", + "username": "${process.env.DATABASE_USERNAME}", + "password": "${process.env.DATABASE_PASSWORD}" + }, + "options": {} + } + } +} +``` + +Edit `server.json` to pick up the deployed hostname from the `HOST` variable in `app.yaml`. + +``` +config/environments/production/server.json +``` + +```json +{ + "host": "${process.env.HOST}", + "port": "${process.env.PORT || 1337}", + "production": true, + "proxy": { + "enabled": false + }, + "cron": { + "enabled": false + }, + "admin": { + "autoOpen": false + } +} +``` + +### Auto-build after deploy + +After deployment, the admin UI has to be re-built. This generates the contents of the `build` folder on the server. + +In `package.json`, add the `gcp-build` command to `scripts`: + +```json +{ + "scripts": { + "gcp-build": "strapi build" + } +} +``` + +### Deploy + +```bash +gcloud app deploy app.yaml --project myapi-123456 +``` + +Watch the logs: + +```bash +gcloud app logs tail --project=myapi-123456 -s default +``` + +Open the admin page and register and admin user. + +``` +https://myapp-123456.appspot.com/admin/ +``` + +### File uploading to Google Cloud Storage + +[Lith/strapi-provider-upload-google-cloud-storage](https://github.com/Lith/strapi-provider-upload-google-cloud-storage) + +```bash +yarn add strapi-provider-upload-google-cloud-storage +``` + +Deploy so that the server app includes the dependency from `package.json`. + +Create a Google service account key. + + + +Save the JSON credentials file. + +Plugins > File Upload > Settings > Production tab + +By default `localhost` is selected. Select the `Google Cloud Storage` plugin. + +Copy the JSON key and set the regions. + +Open the `Cloud Console > Storage > Browser` menu. + +Copy the bucket name to the plugin settings, the default is the app ID, such as `myapi-123456.appspot.com`. + +(Note that the `Access control` setting of the bucket has to be `Fine-grained`, which is the default.) + +Click `Save`, and it's ready to go! + +### Post-setup configuration + +**CORS** + +CORS is enabled by default, allowing `*` origin. You may want to limit the allowed origins. + +``` +config/environments/production/security.json +``` + +**Changing the admin url** + +``` +config/environments/production/server.json +``` + +```json +{ + "admin": { + "path": "/dashboard" + } +} +``` diff --git a/docs/3.0.0-beta.x/admin-panel/customization.md b/docs/3.0.0-beta.x/admin-panel/customization.md index ec08975b27..82f531eac6 100644 --- a/docs/3.0.0-beta.x/admin-panel/customization.md +++ b/docs/3.0.0-beta.x/admin-panel/customization.md @@ -10,19 +10,19 @@ To apply your changes you need to [rebuild](#build) your admin panel By default, the administration panel is exposed via [http://localhost:1337/admin](http://localhost:1337/admin). However, for security reasons, you can easily update this path. -**Path —** `./config/environment/**/server.json`. +**Path —** `./config/server.js`. -```json -{ - "host": "localhost", - "port": 1337, - "cron": { - "enabled": false +```js +module.exports = { + host: 'localhost', + port: 1337, + cron: { + enabled: false, }, - "admin": { - "path": "/dashboard" - } -} + admin: { + path: '/dashboard', + }, +}; ``` The panel will be available through [http://localhost:1337/dashboard](http://localhost:1337/dashboard) with the configurations above. @@ -31,19 +31,19 @@ The panel will be available through [http://localhost:1337/dashboard](http://loc By default, the administration panel client host name is `localhost`. However, you can change this setting by updating the `admin` configuration: -**Path —** `./config/environment/**/server.json`. +**Path —** `./config/server.js`. -```json -{ - "host": "localhost", - "port": 1337, - "cron": { - "enabled": false +```js +module.exports = { + host: 'localhost', + port: 1337, + cron: { + enabled: false, }, - "admin": { - "host": "my-host" - } -} + admin: { + host: 'my-host', + }, +}; ``` ## Development mode @@ -158,19 +158,19 @@ export const SETTINGS_BASE_URL = '/settings'; By default, the front-development server runs on the `8000` port. However, you can change this setting by updating the following configuration: -**Path —** `./config/environment/**/server.json`. +**Path —** `./config/server.js`. -```json -{ - "host": "localhost", - "port": 1337, - "cron": { - "enabled": false +```js +module.exports = { + host: 'localhost', + port: 1337, + cron: { + enabled: false, }, - "admin": { - "port": 3000 - } -} + admin: { + port: 3000, + }, +}; ``` ## Build @@ -205,34 +205,4 @@ strapi build :::: -you can build your admin panel with a specific configuration (located in the `./config/environments/**/server.json`) config by specifying a NODE_ENV as follows: - -:::: tabs - -::: tab yarn - -``` -NODE_ENV=production yarn build -``` - -::: - -::: tab npm - -``` -NODE_ENV=production npm run build -``` - -::: - -::: tab strapi - -``` -NODE_ENV=production strapi build -``` - -::: - -:::: - This will replace the folder's content located at `./build`. Visit [http://localhost:1337/admin](http://localhost:1337/admin) to make sure your updates have been taken into account. diff --git a/docs/3.0.0-beta.x/admin-panel/deploy.md b/docs/3.0.0-beta.x/admin-panel/deploy.md index 246e1494c3..d3a1e0d91c 100644 --- a/docs/3.0.0-beta.x/admin-panel/deploy.md +++ b/docs/3.0.0-beta.x/admin-panel/deploy.md @@ -13,19 +13,19 @@ You don't need to touch anything in your configuration file. This is the default You might want to change the path to access to the administration panel. Here the required configurations to change the path: -**Path —** `./config/environment/**/server.json`. +**Path —** `./config/server.js`. ```js -{ - "host": "localhost", - "port": 1337, - "cron": { - "enabled": false +module.exports = { + host: 'localhost', + port: 1337, + cron: { + enabled: false, }, - "admin": { - "path": "/dashboard" // We change the path to access to the admin (highly recommended for security reasons). - } -} + admin: { + path: '/dashboard', // We change the path to access to the admin (highly recommended for security reasons). + }, +}; ``` **You have to rebuild the administration panel to make this work.** [Build instructions](./customization.md#build). @@ -34,23 +34,23 @@ You might want to change the path to access to the administration panel. Here th It's very common to deploy the front-end and the back-end on different servers. Here are the required configurations to handle this case: -**Path —** `./config/environment/**/server.json`. +**Path —** `./config/server.js`. ```js -{ - "host": "localhost", - "port": 1337, - "cron": { - "enabled": false +module.exports = { + host: 'localhost', + port: 1337, + cron: { + enabled: false, }, - "admin": { - "path": "/", // Note: The administration will be accessible from the root of the domain (ex: http//yourfrontend.com/) - "serveAdminPanel": false, // http://yourbackend.com will not serve any static admin files - "build": { - "backend": "http://yourbackend.com" - } - } -} + admin: { + path: '/', // Note: The administration will be accessible from the root of the domain (ex: http//yourfrontend.com/) + serveAdminPanel: false, // http://yourbackend.com will not serve any static admin files + build: { + backend: 'http://yourbackend.com', + }, + }, +}; ``` The administration URL will be `http://yourfrontend.com` and every request from the panel will hit the backend at `http://yourbackend.com`. @@ -59,22 +59,22 @@ The administration URL will be `http://yourfrontend.com` and every request from In this case, we suppose that you decided to put your administration panel on a different server than the API. -**Path —** `./config/environment/**/server.json`. +**Path —** `./config/server.js`. ```js -{ - "host": "localhost", - "port": 1337, - "cron": { - "enabled": false +module.exports = { + host: 'localhost', + port: 1337, + cron: { + enabled: false, }, - "admin": { - "path": "/dashboard", - "build": { - "backend": "http://yourbackend.com" - } - } -} + admin: { + path: '/dashboard', + build: { + backend: 'http://yourbackend.com', + }, + }, +}; ``` The administration URL will be `http://yourfrontend.com/dashboard` and every request from the panel will hit the backend at `http://yourbackend.com`. diff --git a/docs/3.0.0-beta.x/cli/CLI.md b/docs/3.0.0-beta.x/cli/CLI.md index d44054627f..dd5d5512ef 100644 --- a/docs/3.0.0-beta.x/cli/CLI.md +++ b/docs/3.0.0-beta.x/cli/CLI.md @@ -61,11 +61,6 @@ Start a Strapi application with autoReload disabled. This commands is there to run a Strapi application without restarts and file writes (aimed at production usage). Certain features are disabled in the `strapi start` mode because they require application restarts. -::: tip -You can specify a NODE_ENV to use the configurations in the `./config/environments/[development|staging|production]` folder. -By default the `development` environment will be used. -::: - ## strapi build Builds your admin panel. @@ -83,11 +78,6 @@ options: [--no-optimization] - **strapi build --no-optimization**
Builds the administration panel without minimizing the assets. The build duration is faster. -::: tip -You can specify a NODE_ENV to use the configurations in the `./config/environments/[development|staging|production]` folder. -By default the `development` environment will be used. -::: - ## strapi generate:api Scaffold a complete API with its configurations, controller, model and service. diff --git a/docs/3.0.0-beta.x/concepts/configurations.md b/docs/3.0.0-beta.x/concepts/configurations.md index 8d4d1c3fc8..a7e59bee44 100644 --- a/docs/3.0.0-beta.x/concepts/configurations.md +++ b/docs/3.0.0-beta.x/concepts/configurations.md @@ -187,6 +187,134 @@ module.exports = ({ env }) => ({ | `admin.build` | Admin panel build configuration | | | | `admin.build.backend` | URL that the admin panel and plugins will request | string | | +## Functions + +The `./config/functions/` folder contains a set of JavaScript files in order to add dynamic and logic based configurations. + +All functions that are exposed in this folder are accessible via `strapi.config.functions['fileName']();` + +### Bootstrap + +**Path —** `./config/functions/bootstrap.js`. + +The `bootstrap` function is called at every server start. You can use it to add a specific logic at this moment of your server's lifecycle. + +Here are some use cases: + +- Create an admin user if there isn't one. +- Fill the database with some necessary data. +- Check that the database is up-and-running. +- Load some environment variables. + +The bootstrap function can be synchronous or asynchronous. + +**Synchronous** + +```js +module.exports = () => { + // some sync code +}; +``` + +**Return a promise** + +```js +module.exports = () => { + return new Promise(/* some code */); +}; +``` + +**Asynchronous** + +```js +module.exports = async () => { + await someSetup(); +}; +``` + +### CRON tasks + +CRON tasks allow you to schedule jobs (arbitrary functions) for execution at specific dates, with optional recurrence rules. It only uses a single timer at any given time (rather than reevaluating upcoming jobs every second/minute). + +This feature is powered by [`node-schedule`](https://www.npmjs.com/package/node-schedule) node modules. Check it for more information. + +::: warning +Make sure the `enabled` cron config is set to `true` in `./config/server.js` file. +::: + +The cron format consists of: + +``` +* * * * * * +┬ ┬ ┬ ┬ ┬ ┬ +│ │ │ │ │ | +│ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun) +│ │ │ │ └───── month (1 - 12) +│ │ │ └────────── day of month (1 - 31) +│ │ └─────────────── hour (0 - 23) +│ └──────────────────── minute (0 - 59) +└───────────────────────── second (0 - 59, OPTIONAL) +``` + +To define a CRON job, add your logic like below: + +**Path —** `./config/functions/cron.js`. + +```js +module.exports = { + /** + * Simple example. + * Every monday at 1am. + */ + + '0 0 1 * * 1': () => { + // Add your own logic here (e.g. send a queue of email, create a database backup, etc.). + }, +}; +``` + +### Database ORM customization + +When present, they are loaded to let you customize your database connection instance, for example for adding some plugin, customizing parameters, etc. + +:::: tabs + +::: tab Mongoose + +As an example, for using the `mongoose-simple-random` plugin for MongoDB, you can register it like this: + +**Path —** `./config/functions/mongoose.js`. + +```js +'use strict'; + +const random = require('mongoose-simple-random'); + +module.exports = (mongoose, connection) => { + mongoose.plugin(random); +}; +``` + +::: + +::: tab Bookshelf + +Another example would be using the `bookshelf-uuid` plugin for MySQL, you can register it like this: + +**Path —** `./config/functions/bookshelf.js`. + +```js +'use strict'; + +module.exports = (bookshelf, connection) => { + bookshelf.plugin(require('bookshelf-uuid')); +}; +``` + +::: + +:::: + ## Database This file lets you define database connections that will be used to store your application content. @@ -363,134 +491,6 @@ module.exports = ({ env }) => ({ Take a look at the [database's guide](../guides/databases.md) for more details. ::: -## Functions - -The `./config/functions/` folder contains a set of JavaScript files in order to add dynamic and logic based configurations. - -All functions that are exposed in this folder are accessible via `strapi.config.functions['fileName']();` - -### Bootstrap - -**Path —** `./config/functions/bootstrap.js`. - -The `bootstrap` function is called at every server start. You can use it to add a specific logic at this moment of your server's lifecycle. - -Here are some use cases: - -- Create an admin user if there isn't one. -- Fill the database with some necessary data. -- Check that the database is up-and-running. -- Load some environment variables. - -The bootstrap function can be synchronous or asynchronous. - -**Synchronous** - -```js -module.exports = () => { - // some sync code -}; -``` - -**Return a promise** - -```js -module.exports = () => { - return new Promise(/* some code */); -}; -``` - -**Asynchronous** - -```js -module.exports = async () => { - await someSetup(); -}; -``` - -### CRON tasks - -CRON tasks allow you to schedule jobs (arbitrary functions) for execution at specific dates, with optional recurrence rules. It only uses a single timer at any given time (rather than reevaluating upcoming jobs every second/minute). - -This feature is powered by [`node-schedule`](https://www.npmjs.com/package/node-schedule) node modules. Check it for more information. - -::: warning -Make sure the `enabled` cron config is set to `true` in `./config/environments/**/server.json` file. -::: - -The cron format consists of: - -``` -* * * * * * -┬ ┬ ┬ ┬ ┬ ┬ -│ │ │ │ │ | -│ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun) -│ │ │ │ └───── month (1 - 12) -│ │ │ └────────── day of month (1 - 31) -│ │ └─────────────── hour (0 - 23) -│ └──────────────────── minute (0 - 59) -└───────────────────────── second (0 - 59, OPTIONAL) -``` - -To define a CRON job, add your logic like below: - -**Path —** `./config/functions/cron.js`. - -```js -module.exports = { - /** - * Simple example. - * Every monday at 1am. - */ - - '0 0 1 * * 1': () => { - // Add your own logic here (e.g. send a queue of email, create a database backup, etc.). - }, -}; -``` - -### Database ORM customization - -When present, they are loaded to let you customize your database connection instance, for example for adding some plugin, customizing parameters, etc. - -:::: tabs - -::: tab Mongoose - -As an example, for using the `mongoose-simple-random` plugin for MongoDB, you can register it like this: - -**Path —** `./config/functions/mongoose.js`. - -```js -'use strict'; - -const random = require('mongoose-simple-random'); - -module.exports = (mongoose, connection) => { - mongoose.plugin(random); -}; -``` - -::: - -::: tab Bookshelf - -Another example would be using the `bookshelf-uuid` plugin for MySQL, you can register it like this: - -**Path —** `./config/functions/bookshelf.js`. - -```js -'use strict'; - -module.exports = (bookshelf, connection) => { - bookshelf.plugin(require('bookshelf-uuid')); -}; -``` - -::: - -:::: - ## Configuration in database Configuration files are not multi server friendly. So we created a data store for config you will want to update in production. diff --git a/docs/3.0.0-beta.x/concepts/hooks.md b/docs/3.0.0-beta.x/concepts/hooks.md index ca9db504b4..ab1fe3a986 100644 --- a/docs/3.0.0-beta.x/concepts/hooks.md +++ b/docs/3.0.0-beta.x/concepts/hooks.md @@ -77,14 +77,14 @@ The framework allows to load hooks from the project directly without having to i ## Configuration and activation -To activate and configure your hook with custom options, you need to edit your `./config/environments/**/hook.json` file in your Strapi app. +To activate and configure your hook with custom options, you need to edit your `./config/hook.js` file in your Strapi app. -```javascript -{ - ... - "hook-name": { - "enabled": true, - ... - } -} +```js +module.exports = { + settings: { + 'hook-name': { + enabled: true, + }, + }, +}; ``` diff --git a/docs/3.0.0-beta.x/concepts/middlewares.md b/docs/3.0.0-beta.x/concepts/middlewares.md index 798c38e205..7a08d440d9 100644 --- a/docs/3.0.0-beta.x/concepts/middlewares.md +++ b/docs/3.0.0-beta.x/concepts/middlewares.md @@ -119,8 +119,6 @@ The following middlewares cannot be disabled: responses, router, logger and boom ### Request middlewares -**Path —** `./config/environments/**/request.json`. - - `session` - `enabled` (boolean): Enable or disable sessions. Default value: `false`. - `client` (string): Client used to persist sessions. Default value: `redis`. @@ -143,8 +141,6 @@ The session doesn't work with `mongo` as a client. The package that we should us ## Response middlewares -**Path —** `./config/environments/**/response.json`. - - [`gzip`](https://en.wikipedia.org/wiki/Gzip) - `enabled` (boolean): Enable or not GZIP response compression. - `responseTime` @@ -155,8 +151,6 @@ The session doesn't work with `mongo` as a client. The package that we should us ### Security middlewares -**Path —** `./config/environments/**/security.json`. - - [`csp`](https://en.wikipedia.org/wiki/Content_Security_Policy) - `enabled` (boolean): Enable or disable CSP to avoid Cross Site Scripting (XSS) and data injection attacks. - [`p3p`](https://en.wikipedia.org/wiki/P3P) @@ -185,7 +179,7 @@ The session doesn't work with `mongo` as a client. The package that we should us ### Load order -The middlewares are injected into the Koa stack asynchronously. Sometimes it happens that some of these middlewares need to be loaded in a specific order. To define a load order, we created a dedicated file located in `./config/middleware.json`. +The middlewares are injected into the Koa stack asynchronously. Sometimes it happens that some of these middlewares need to be loaded in a specific order. To define a load order, we created a dedicated file located in `./config/middleware.js`. **Path —** `./config/middleware.js`. diff --git a/docs/3.0.0-beta.x/concepts/models.md b/docs/3.0.0-beta.x/concepts/models.md index 61420edf26..740682ecb5 100644 --- a/docs/3.0.0-beta.x/concepts/models.md +++ b/docs/3.0.0-beta.x/concepts/models.md @@ -130,7 +130,7 @@ Additional settings can be set on models: } ``` -In this example, the model `Restaurant` will be accessible through the `Restaurants` global variable. The data will be stored in the `Restaurants_v1` collection or table and the model will use the `mongo` connection defined in `./config/environments/**/database.json` +In this example, the model `Restaurant` will be accessible through the `Restaurants` global variable. The data will be stored in the `Restaurants_v1` collection or table and the model will use the `mongo` connection defined in `./config/database.js` ::: warning If not set manually in the JSON file, Strapi will adopt the filename as `globalId`. diff --git a/docs/3.0.0-beta.x/concepts/webhooks.md b/docs/3.0.0-beta.x/concepts/webhooks.md index 7be2d925e7..cb27a5ca8c 100644 --- a/docs/3.0.0-beta.x/concepts/webhooks.md +++ b/docs/3.0.0-beta.x/concepts/webhooks.md @@ -211,21 +211,21 @@ This event is triggered only when you delete a media through the media interface ### Available configurations -You can set webhook configurations inside the file `./config/environments/{env}/server.json`. +You can set webhook configurations inside the file `./config/server.js`. - `webhooks` - `defaultHeaders`: You can set default headers to use for your webhook requests. This option is overwritten by the headers set in the webhook itself. **Example configuration** -```json -{ - "webhooks": { - "defaultHeaders": { - "Custom-Header": "my-custom-header" - } - } -} +```js +module.exports = { + webhooks: { + defaultHeaders: { + 'Custom-Header': 'my-custom-header', + }, + }, +}; ``` ### Securing your webhooks @@ -235,34 +235,34 @@ Most of the time, webhooks make requests to public URLs, therefore it is possibl To prevent this from happening you can send a header with an authentication token. Using the Admin panel you would have to do it for every webhook. Another way is to define `defaultHeaders` to add to every webhook requests. -You can configure these global headers by updating the file at `./config/environments/{env}/server.json`: +You can configure these global headers by updating the file at `./config/server.js`: :::: tabs ::: tab "Simple token" -```json -{ - "webhooks": { - "defaultHeaders": { - "Authorization": "Bearer my-very-secured-token" - } - } -} +```js +module.exports = { + webhooks: { + defaultHeaders: { + Authorization: 'Bearer my-very-secured-token', + }, + }, +}; ``` ::: ::: tab "Environment variable" -```json -{ - "webhooks": { - "defaultHeaders": { - "Authorization": "Bearer ${ process.env.WEBHOOK_TOKEN }" - } - } -} +```js +module.exports = { + webhooks: { + defaultHeaders: { + Authorization: `Bearer ${process.env.WEBHOOK_TOKEN}`, + }, + }, +}; ``` :::: diff --git a/docs/3.0.0-beta.x/guides/client.md b/docs/3.0.0-beta.x/guides/client.md index 128fce5860..a05e2a670d 100644 --- a/docs/3.0.0-beta.x/guides/client.md +++ b/docs/3.0.0-beta.x/guides/client.md @@ -44,15 +44,16 @@ module.exports = strapi => { When the hook is created, we have to enable it to say to Strapi to use this hook. -**Path —** `./config/hook.json` +**Path —** `./config/hook.js` -```json -{ - ... - "github": { - "enabled": true - } -} +```js +module.exports = { + settings: { + github: { + enabled: true, + }, + }, +}; ``` Now you can start your application, you should see a log `my hook is loaded` in your terminal. @@ -62,16 +63,23 @@ Now you can start your application, you should see a log `my hook is loaded` in First lets update the config file to add your [GitHub token](https://github.com/settings/tokens). By following the [documentation](https://octokit.github.io/rest.js/#authentication) you will also find the way to use GitHub applications. -**Path —** `./config/hook.json` +**Path —** `./config/hook.js` -```json -{ - ... - "github": { - "enabled": true, - "token": "bf78d4fc3c1767019870476d6d7cc8961383d80f" - } -} +```js +module.exports = { + settings: { + github: { + enabled: true, + token: process.env.GITHUB_TOKEN, + }, + }, +}; +``` + +**Path -** `.env` + +``` +GITHUB_TOKEN=bf78d4fc3c1767019870476d6d7cc8961383d80f ``` Now we have to load the GitHub client. @@ -84,10 +92,10 @@ const GitHubAPI = require('@octokit/rest'); module.exports = strapi => { return { async initialize() { - const { token } = strapi.config.hook.github; + const { token } = strapi.config.get('hook.settings.github'); strapi.services.github = new GitHubAPI({ - userAgent: `${strapi.config.info.name} v${strapi.config.info.version}`, + userAgent: `${strapi.config.get('info.name')} v${strapi.config.get('info.version')}`, auth: `token ${token}`, }); }, @@ -111,43 +119,3 @@ module.exports = async () => { ``` Restart your server and you should see your GitHub profile data. - -## Configs by environment - -You would probably want specific configurations for development and production environment. - -To do so, we will update some configurations. - -You have to move your `github` configs from `./config/hook.json` to `./config/environments/development.json`, then remove it from the `hook.json` file. - -And in your GitHub hook, you will have to replace `strapi.config.hook.github` by `strapi.config.currentEnvironment.github` to access to the configs. - -**Path —** `./config/environments/development.json` - -```json -{ - "github": { - "enabled": true, - "token": "806506ab855a94e8608148315eeb39a44c29aee1" - } -} -``` - -**Path —** `./hooks/github/index.js` - -```js -const GitHubAPI = require('@octokit/rest'); - -module.exports = strapi => { - return { - async initialize() { - const { token } = strapi.config.currentEnvironment.github; - - strapi.services.github = new GitHubAPI({ - userAgent: `${strapi.config.info.name} v${strapi.config.info.version}`, - auth: `token ${token}`, - }); - }, - }; -}; -``` diff --git a/docs/3.0.0-beta.x/guides/databases.md b/docs/3.0.0-beta.x/guides/databases.md index fcf0f8bcd6..f7652887e2 100644 --- a/docs/3.0.0-beta.x/guides/databases.md +++ b/docs/3.0.0-beta.x/guides/databases.md @@ -313,23 +313,29 @@ Please note the `` after your `username`. In this example, after `mong Replace the contents of `/database.json` with the following and replace **< password >** with the password of the user of your database you created earlier: -`Path: ./config/environments/(development|production)/database.json`. +`Path: ./config/database.js`. -```json -{ - "defaultConnection": "default", - "connections": { - "default": { - "connector": "mongoose", - "settings": { - "uri": "mongodb://paulbocuse:@strapidatabase-shard-00-00-fxxx6c.mongodb.net:27017,strapidatabase-shard-00-01-fxxxc.mongodb.net:27017,strapidatabase-shard-00-02-fxxxc.mongodb.net:27017/test?ssl=true&replicaSet=strapidatabase-shard-0&authSource=admin&retryWrites=true&w=majority" +```js +module.exports = ({ env }) => ({ + defaultConnection: 'default', + connections: { + default: { + connector: 'mongoose', + settings: { + uri: env('DATABASE_URI'), }, - "options": { - "ssl": true - } - } - } -} + options: { + ssl: true, + }, + }, + }, +}); +``` + +`Path: .env` + +``` +DATABASE_URI=mongodb://paulbocuse:@strapidatabase-shard-00-00-fxxx6c.mongodb.net:27017,strapidatabase-shard-00-01-fxxxc.mongodb.net:27017,strapidatabase-shard-00-02-fxxxc.mongodb.net:27017/test?ssl=true&replicaSet=strapidatabase-shard-0&authSource=admin&retryWrites=true&w=majority ``` ::: warning NOTE diff --git a/docs/3.0.0-beta.x/guides/error-catching.md b/docs/3.0.0-beta.x/guides/error-catching.md index 0182c9d8c7..fbf211d62e 100644 --- a/docs/3.0.0-beta.x/guides/error-catching.md +++ b/docs/3.0.0-beta.x/guides/error-catching.md @@ -67,28 +67,26 @@ It's important to call `throw(error);` to avoid stopping the middleware stack. I Make sure your middleware is added at the end of the middleware stack. -**Path —** `./config/middleware.json` +**Path —** `./config/middleware.js` -```json -{ - ... - "after": [ - "parser", - "router", - "sentry" - ] - } -} +```js +module.exports = { + load: { + after: ['parser', 'router', 'sentry'], + }, +}; ``` And finally you have to enable the middleware. -**Path —** `./config/environments/**/middleware.json` +**Path —** `./config/middleware.js` -```json -{ - "sentry": { - "enabled": true - } -} +```js +module.exports = { + settings: { + sentry: { + enabled: true, + }, + }, +}; ``` diff --git a/docs/3.0.0-beta.x/guides/scheduled-publication.md b/docs/3.0.0-beta.x/guides/scheduled-publication.md index 4861311335..233bee8f0d 100644 --- a/docs/3.0.0-beta.x/guides/scheduled-publication.md +++ b/docs/3.0.0-beta.x/guides/scheduled-publication.md @@ -38,7 +38,7 @@ module.exports = { }; ``` -Make sure the enabled cron config is set to true in `./config/environments/**/server.json` file. +Make sure the enabled cron config is set to true in `./config/server.js` file. ::: tip Please note that Strapi's built in CRON feature will not work if you plan to use `pm2` or node based clustering. You will need to execute these CRON tasks outside of Strapi. @@ -58,20 +58,15 @@ module.exports = { // fetch articles to publish const draftArticleToPublish = await strapi.api.article.services.article.find({ status: 'draft', - publish_at_lt: new Date() + publish_at_lt: new Date(), }); // update status of articles - draftArticleToPublish.forEach(async (article) => { - await strapi.api.article.services.article.update( - {id: article.id}, - {status: 'published'} - ); + draftArticleToPublish.forEach(async article => { + await strapi.api.article.services.article.update({ id: article.id }, { status: 'published' }); }); }, }; ``` And tada! - - diff --git a/docs/3.0.0-beta.x/installation/digitalocean-one-click.md b/docs/3.0.0-beta.x/installation/digitalocean-one-click.md index a5f0d14e3c..3d7f06fadc 100644 --- a/docs/3.0.0-beta.x/installation/digitalocean-one-click.md +++ b/docs/3.0.0-beta.x/installation/digitalocean-one-click.md @@ -27,7 +27,7 @@ To create a project head over to the Strapi [listing on the marketplace](https:/ ### Step 3: Visit your app -Please note that it may take anywhere from 30 seconds to a few minutes for the droplet to startup, when it does you should see it in your [droplets list](https://cloud.digitalocean.com/droplets). +Please note that it may take anywhere from 30 seconds to a few minutes for the droplet to startup, when it does you should see it in your [droplets list](https://cloud.digitalocean.com/droplets). ::: warning After the droplet has started, it will take a few more minutes to finish the Strapi installation. @@ -151,19 +151,10 @@ pm2 stop strapi-develop psql -c "ALTER USER strapi with password 'your-new-password';" ``` -- Update the `/srv/strapi/strapi/config/environments/development/database.json` file with the new password. +- Update the `/srv/strapi/strapi/config/.env` file with the new password. -```json -... -"settings": { - "client": "postgres", - "host": "127.0.0.1", - "port": "5432", - "database": "strapi", - "username": "strapi", - "password": "your-new-password" -}, -... +``` +DATABASE_PASSWORD=your-new-password ``` - Restart Strapi and confirm the password change was successful diff --git a/docs/3.0.0-beta.x/plugins/users-permissions.md b/docs/3.0.0-beta.x/plugins/users-permissions.md index 89263c66fb..6fc1698ae3 100644 --- a/docs/3.0.0-beta.x/plugins/users-permissions.md +++ b/docs/3.0.0-beta.x/plugins/users-permissions.md @@ -745,5 +745,5 @@ You can update these templates under **Plugins** > **Roles & Permissions** > **E JWT tokens can be verified and trusted because the information is digitally signed. To sign a token a _secret_ is required. By default Strapi generates one that is stored in `./your-app/extensions/users-permissions/config/jwt.json`. This is useful during development but for security reasons it is **recommended** to set a custom token via an environment variable `JWT_SECRET` when deploying to production. It is also possible to modify `jwt.json` file to accept `JWT_TOKEN` automatically by doing following ([docs](https://strapi.io/documentation/3.0.0-beta.x/concepts/configurations.html#dynamic-configurations)). ``` - "jwtSecret": "${process.env.JWT_SECRET}" +"jwtSecret": "${process.env.JWT_SECRET}" ```