Domains Help

Type of Record What it’s for
A Record Connects an IP Address to a host name
CNAME Record Allows more than one DNS name for a host
MX Record Ensures email is delivered to the right location
NS Record Contains the nameserver info
TXT Record Provides additional info about a host or more technical info to servers
SRV Record Finds computers that host specific services
AAAA Record Provides IP addresses that do not fit a standard A Record format
SPF Record Used to help prevent against spam
CAA Record Used to prevent anyone from obtaining an unauthorized SSL certificate for your domain

How To Install Linux, Nginx, MySQL, PHP (LEMP stack) in Ubuntu

Introduction

The LEMP software stack is a group of software that can be used to serve dynamic web pages and web applications. This is an acronym that describes a Linux operating system, with an Nginx web server. The backend data is stored in the MySQL database and the dynamic processing is handled by PHP.

In this guide, we will demonstrate how to install a LEMP stack on an Ubuntu 16.04 server. The Ubuntu operating system takes care of the first requirement. We will describe how to get the rest of the components up and running.

Prerequisites

Before you complete this tutorial, you should have a regular, non-root user account on your server with sudo privileges. You can learn how to set up this type of account by completing our Ubuntu 16.04 initial server setup.

Once you have your user available, sign into your server with that username. You are now ready to begin the steps outlined in this guide.

Step 1: Install the Nginx Web Server

In order to display web pages to our site visitors, we are going to employ Nginx, a modern, efficient web server.

All of the software we will be using for this procedure will come directly from Ubuntu’s default package repositories. This means we can use the apt package management suite to complete the installation.

Since this is our first time using apt for this session, we should start off by updating our local package index. We can then install the server:

  • sudo apt-get update
  • sudo apt-get install nginx

On Ubuntu 16.04, Nginx is configured to start running upon installation.

If you have the ufw firewall running, as outlined in our initial setup guide, you will need to allow connections to Nginx. Nginx registers itself with ufw upon installation, so the procedure is rather straight forward.

It is recommended that you enable the most restrictive profile that will still allow the traffic you want. Since we haven’t configured SSL for our server yet, in this guide, we will only need to allow traffic on port 80.

You can enable this by typing:

  • sudo ufw allow ‘Nginx HTTP’

You can verify the change by typing:

  • sudo ufw status

You should see HTTP traffic allowed in the displayed output:

Output
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere                  
Nginx HTTP                 ALLOW       Anywhere                  
OpenSSH (v6)               ALLOW       Anywhere (v6)             
Nginx HTTP (v6)            ALLOW       Anywhere (v6)

With the new firewall rule added, you can test if the server is up and running by accessing your server’s domain name or public IP address in your web browser.

If you do not have a domain name pointed at your server and you do not know your server’s public IP address, you can find it by typing one of the following into your terminal:

  • ip addr show eth0 | grep inet | awk ‘{ print $2; }’ | sed ‘s/\/.*$//’

This will print out a few IP addresses. You can try each of them in turn in your web browser.

As an alternative, you can check which IP address is accessible as viewed from other locations on the internet:

  • curl -4 icanhazip.com

Type one of the addresses that you receive in your web browser. It should take you to Nginx’s default landing page:

http://server_domain_or_IP

Nginx default page

If you see the above page, you have successfully installed Nginx.

Step 2: Install MySQL to Manage Site Data

Now that we have a web server, we need to install MySQL, a database management system, to store and manage the data for our site.

You can install this easily by typing:

  • sudo apt-get install mysql-server

You will be asked to supply a root (administrative) password for use within the MySQL system.

The MySQL database software is now installed, but its configuration is not exactly complete yet.

To secure the installation, we can run a simple security script that will ask whether we want to modify some insecure defaults. Begin the script by typing:

  • mysql_secure_installation

You will be asked to enter the password you set for the MySQL root account. Next, you will be asked if you want to configure the VALIDATE PASSWORD PLUGIN.

Warning: Enabling this feature is something of a judgment call. If enabled, passwords which don’t match the specified criteria will be rejected by MySQL with an error. This will cause issues if you use a weak password in conjunction with software which automatically configures MySQL user credentials, such as the Ubuntu packages for phpMyAdmin. It is safe to leave validation disabled, but you should always use strong, unique passwords for database credentials.

Answer y for yes, or anything else to continue without enabling.

VALIDATE PASSWORD PLUGIN can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD plugin?

Press y|Y for Yes, any other key for No:

If you’ve enabled validation, you’ll be asked to select a level of password validation. Keep in mind that if you enter 2, for the strongest level, you will receive errors when attempting to set any password which does not contain numbers, upper and lowercase letters, and special characters, or which is based on common dictionary words.

There are three levels of password validation policy:

LOW    Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary                  file

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 1

If you enabled password validation, you’ll be shown a password strength for the existing root password, and asked you if you want to change that password. If you are happy with your current password, enter nfor “no” at the prompt:

Using existing password for root.

Estimated strength of the password: 100
Change the password for root ? ((Press y|Y for Yes, any other key for No) : n

For the rest of the questions, you should press Y and hit the Enter key at each prompt. This will remove some anonymous users and the test database, disable remote root logins, and load these new rules so that MySQL immediately respects the changes we have made.

At this point, your database system is now set up and we can move on.

Step 3: Install PHP for Processing

We now have Nginx installed to serve our pages and MySQL installed to store and manage our data. However, we still don’t have anything that can generate dynamic content. We can use PHP for this.

Since Nginx does not contain native PHP processing like some other web servers, we will need to install php-fpm, which stands for “fastCGI process manager”. We will tell Nginx to pass PHP requests to this software for processing.

We can install this module and will also grab an additional helper package that will allow PHP to communicate with our database backend. The installation will pull in the necessary PHP core files. Do this by typing:

  • sudo apt-get install php-fpm php-mysql

Configure the PHP Processor

We now have our PHP components installed, but we need to make a slight configuration change to make our setup more secure.

Open the main php-fpm configuration file with root privileges:

  • sudo nano /etc/php/7.0/fpm/php.ini

What we are looking for in this file is the parameter that sets cgi.fix_pathinfo. This will be commented out with a semi-colon (;) and set to “1” by default.

This is an extremely insecure setting because it tells PHP to attempt to execute the closest file it can find if the requested PHP file cannot be found. This basically would allow users to craft PHP requests in a way that would allow them to execute scripts that they shouldn’t be allowed to execute.

We will change both of these conditions by uncommenting the line and setting it to “0” like this:

/etc/php/7.0/fpm/php.ini
cgi.fix_pathinfo=0

Save and close the file when you are finished.

Now, we just need to restart our PHP processor by typing:

  • sudo systemctl restart php7.0-fpm

This will implement the change that we made.

Step 4: Configure Nginx to Use the PHP Processor

Now, we have all of the required components installed. The only configuration change we still need is to tell Nginx to use our PHP processor for dynamic content.

We do this on the server block level (server blocks are similar to Apache’s virtual hosts). Open the default Nginx server block configuration file by typing:

  • sudo nano /etc/nginx/sites-available/default

Currently, with the comments removed, the Nginx default server block file looks like this:

/etc/nginx/sites-available/default
server {
    listen 80 default_server;
    listen [::]:80 default_server;

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

    server_name _;

    location / {
        try_files $uri $uri/ =404;
    }
}

We need to make some changes to this file for our site.

  • First, we need to add index.php as the first value of our index directive so that files named index.php are served, if available, when a directory is requested.
  • We can modify the server_name directive to point to our server’s domain name or public IP address.
  • For the actual PHP processing, we just need to uncomment a segment of the file that handles PHP requests by removing the pound symbols (#) from in front of each line. This will be the location ~\.php$ location block, the included fastcgi-php.conf snippet, and the socket associated with php-fpm.
  • We will also uncomment the location block dealing with .htaccess files using the same method. Nginx doesn’t process these files. If any of these files happen to find their way into the document root, they should not be served to visitors.

The changes that you need to make are in red in the text below:

/etc/nginx/sites-available/default
server {
    listen 80 default_server;
    listen [::]:80 default_server;

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

    server_name server_domain_or_IP;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }

    location ~ /\.ht {
        deny all;
    }
}

When you’ve made the above changes, you can save and close the file.

Test your configuration file for syntax errors by typing:

  • sudo nginx -t

If any errors are reported, go back and recheck your file before continuing.

When you are ready, reload Nginx to make the necessary changes:

  • sudo systemctl reload nginx

Step 5: Create a PHP File to Test Configuration

Your LEMP stack should now be completely set up. We can test it to validate that Nginx can correctly hand .php files off to our PHP processor.

We can do this by creating a test PHP file in our document root. Open a new file called info.php within your document root in your text editor:

  • sudo nano /var/www/html/info.php

Type or paste the following lines into the new file. This is valid PHP code that will return information about our server:

/var/www/html/info.php
<?php
phpinfo();

When you are finished, save and close the file.

Now, you can visit this page in your web browser by visiting your server’s domain name or public IP address followed by /info.php:

http://server_domain_or_IP/info.php

You should see a web page that has been generated by PHP with information about your server:

PHP page info

If you see a page that looks like this, you’ve set up PHP processing with Nginx successfully.

After verifying that Nginx renders the page correctly, it’s best to remove the file you created as it can actually give unauthorized users some hints about your configuration that may help them try to break in. You can always regenerate this file if you need it later.

For now, remove the file by typing:

  • sudo rm /var/www/html/info.php

Conclusion

You should now have a LEMP stack configured on your Ubuntu 16.04 server. This gives you a very flexible foundation for serving web content to your visitors.

reposted from DigitalOcean

How To Install WordPress with LEMP on Ubuntu

Introduction

WordPress is the most popular CMS (content management system) on the internet. It allows you to easily set up flexible blogs and websites on top of a MySQL backend with PHP processing. WordPress has seen incredible adoption and is a great choice for getting a website up and running quickly. After setup, almost all administration can be done through the web frontend.

In this guide, we’ll focus on getting a WordPress instance set up on a LEMP stack (Linux, Nginx, MySQL, and PHP) on an Ubuntu 16.04 server.

Prerequisites

In order to complete this tutorial, you will need access to an Ubuntu 16.04 server.

You will need to perform the following tasks before you can start this guide:

  • Create a sudo user on your server: We will be completing the steps in this guide using a non-root user with sudo privileges. You can create a user with sudo privileges by following our Ubuntu 16.04 initial server setup guide.
  • Install a LEMP stack: WordPress will need a web server, a database, and PHP in order to correctly function. Setting up a LEMP stack (Linux, Nginx, MySQL, and PHP) fulfills all of these requirements. Follow this guide to install and configure this software.
  • Secure your site with SSL: WordPress serves dynamic content and handles user authentication and authorization. TLS/SSL is the technology that allows you to encrypt the traffic from your site so that your connection is secure. The way you set up SSL will depend on whether you have a domain name for your site.
    • If you have a domain name… the easiest way to secure your site is with Let’s Encrypt, which provides free, trusted certificates. Follow our Let’s Encrypt guide for Nginx to set this up.
    • If you do not have a domain… and you are just using this configuration for testing or personal use, you can use a self-signed certificate instead. This provides the same type of encryption, but without the domain validation. Follow our self-signed SSL guide for Nginx to get set up.

When you are finished the setup steps, log into your server as your sudo user and continue below.

Step 1: Create a MySQL Database and User for WordPress

The first step that we will take is a preparatory one. WordPress uses MySQL to manage and store site and user information. We have MySQL installed already, but we need to make a database and a user for WordPress to use.

To get started, log into the MySQL root (administrative) account by issuing this command:

  • mysql -u root -p

You will be prompted for the password you set for the MySQL root account when you installed the software.

First, we can create a separate database that WordPress can control. You can call this whatever you would like, but we will be using wordpress in this guide to keep it simple. You can create the database for WordPress by typing:

  • CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
Note

Every MySQL statement must end in a semi-colon (;). Check to make sure this is present if you are running into any issues.

Next, we are going to create a separate MySQL user account that we will use exclusively to operate on our new database. Creating one-function databases and accounts is a good idea from a management and security standpoint. We will use the name wordpressuser in this guide. Feel free to change this if you’d like.

We are going to create this account, set a password, and grant access to the database we created. We can do this by typing the following command. Remember to choose a strong password here for your database user:

  • GRANT ALL ON wordpress.* TO ‘wordpressuser‘@’localhost’ IDENTIFIED BY ‘password‘;

You now have a database and user account, each made specifically for WordPress. We need to flush the privileges so that the current instance of MySQL knows about the recent changes we’ve made:

  • FLUSH PRIVILEGES;

Exit out of MySQL by typing:

  • EXIT;

Step 2: Adjust Nginx’s Configuration to Correctly Handle WordPress

Next, we will be making a few minor adjustments to our Nginx server block files.

Open the default server block file with sudo privileges to begin:

  • sudo nano /etc/nginx/sites-available/default

Within the main server block, we need to add a few location blocks.

Start by creating exact-matching location blocks for requests to /favicon.ico and /robots.txt, both of which we do not want to log requests for.

We will use a regular expression location to match any requests for static files. We will again turn off the logging for these requests and will mark them as highly cacheable since these are typically expensive resources to serve. You can adjust this static files list to contain any other file extensions your site may use:

/etc/nginx/sites-available/default
server {
    . . .

    location = /favicon.ico { log_not_found off; access_log off; }
    location = /robots.txt { log_not_found off; access_log off; allow all; }
    location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ {
        expires max;
        log_not_found off;
    }
    . . .
}

Inside of the existing location / block, we need to adjust the try_files list so that instead of returning a 404 error as the default option, control is passed to the index.php file with the request arguments.

This should look something like this:

/etc/nginx/sites-available/default
server {
    . . .
    location / {
        #try_files $uri $uri/ =404;
        try_files $uri $uri/ /index.php$is_args$args;
    }
    . . .
}

When you are finished, save and close the file.

Now, we can check our configuration for syntax errors by typing:

  • sudo nginx -t

If no errors were reported, reload Nginx by typing:

  • sudo systemctl reload nginx

Step 3: Install Additional PHP Extensions

When setting up our LEMP stack, we only required a very minimal set of extensions in order to get PHP to communicate with MySQL. WordPress and many of its plugins leverage additional PHP extensions.

We can download and install some of the most popular PHP extensions for use with WordPress by typing:

  • sudo apt-get update
  • sudo apt-get install php-curl php-gd php-mbstring php-mcrypt php-xml php-xmlrpc
Note

Each WordPress plugin has its own set of requirements. Some may require additional PHP packages to be installed. Check your plugin documentation to discover its PHP requirements. If they are available, they can be installed with apt-get as demonstrated above.

When you are finished installing the extensions, restart the PHP-FPM process so that the running PHP processor can leverage the newly installed features:

  • sudo systemctl restart php7.0-fpm

Step 4: Download WordPress

Now that our server software is configured, we can download and set up WordPress. For security reasons in particular, it is always recommended to get the latest version of WordPress from their site.

Change into a writable directory and then download the compressed release by typing:

  • cd /tmp
  • curl -O https://wordpress.org/latest.tar.gz

Extract the compressed file to create the WordPress directory structure:

  • tar xzvf latest.tar.gz

We will be moving these files into our document root momentarily. Before we do that, we can copy over the sample configuration file to the filename that WordPress actually reads:

  • cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php

We can also create the upgrade directory, so that WordPress won’t run into permissions issues when trying to do this on its own following an update to its software:

  • mkdir /tmp/wordpress/wp-content/upgrade

Now, we can copy the entire contents of the directory into our document root. We are using the -a flag to make sure our permissions are maintained. We are using a dot at the end of our source directory to indicate that everything within the directory should be copied, including any hidden files:

  • sudo cp -a /tmp/wordpress/. /var/www/html

Step 5: Configure the WordPress Directory

Before we do the web-based WordPress setup, we need to adjust some items in our WordPress directory.

Adjusting the Ownership and Permissions

One of the big things we need to accomplish is setting up reasonable file permissions and ownership. We need to be able to write to these files as a regular user, and we need the web server to also be able to access and adjust certain files and directories in order to function correctly.

We’ll start by assigning ownership over all of the files in our document root to our username. We will use sammy as our username in this guide, but you should change this to match whatever your sudo user is called. We will assign group ownership to the www-data group:

  • sudo chown -R sammy:www-data /var/www/html

Next, we will set the setgid bit on each of the directories within the document root. This causes new files created within these directories to inherit the group of the parent directory (which we just set to www-data) instead of the creating user’s primary group. This just makes sure that whenever we create a file in the directory on the command line, the web server will still have group ownership over it.

We can set the setgid bit on every directory in our WordPress installation by typing:

  • sudo find /var/www/html -type d -exec chmod g+s {} \;

There are a few other fine-grained permissions we’ll adjust. First, we’ll give group write access to the wp-content directory so that the web interface can make theme and plugin changes:

  • sudo chmod g+w /var/www/html/wp-content

As part of this process, we will give the web server write access to all of the content in these two directories:

  • sudo chmod -R g+w /var/www/html/wp-content/themes
  • sudo chmod -R g+w /var/www/html/wp-content/plugins

This should be a reasonable permissions set to start with. Some plugins and procedures might require additional tweaks.

Setting up the WordPress Configuration File

Now, we need to make some changes to the main WordPress configuration file.

When we open the file, our first order of business will be to adjust some secret keys to provide some security for our installation. WordPress provides a secure generator for these values so that you do not have to try to come up with good values on your own. These are only used internally, so it won’t hurt usability to have complex, secure values here.

To grab secure values from the WordPress secret key generator, type:

  • curl -s https://api.wordpress.org/secret-key/1.1/salt/

You will get back unique values that look something like this:

Warning

It is important that you request unique values each time. Do NOT copy the values shown below!

Output
define('AUTH_KEY',         '1jl/vqfs<XhdXoAPz9 DO NOT COPY THESE VALUES c_j{iwqD^<+c9.k<J@4H');
define('SECURE_AUTH_KEY',  'E2N-h2]Dcvp+aS/p7X DO NOT COPY THESE VALUES {Ka(f;rv?Pxf})CgLi-3');
define('LOGGED_IN_KEY',    'W(50,{W^,OPB%PB<JF DO NOT COPY THESE VALUES 2;y&,2m%3]R6DUth[;88');
define('NONCE_KEY',        'll,4UC)7ua+8<!4VM+ DO NOT COPY THESE VALUES #`DXF+[$atzM7 o^-C7g');
define('AUTH_SALT',        'koMrurzOA+|L_lG}kf DO NOT COPY THESE VALUES  07VC*Lj*lD&?3w!BT#-');
define('SECURE_AUTH_SALT', 'p32*p,]z%LZ+pAu:VY DO NOT COPY THESE VALUES C-?y+K0DK_+F|0h{!_xY');
define('LOGGED_IN_SALT',   'i^/G2W7!-1H2OQ+t$3 DO NOT COPY THESE VALUES t6**bRVFSD[Hi])-qS`|');
define('NONCE_SALT',       'Q6]U:K?j4L%Z]}h^q7 DO NOT COPY THESE VALUES 1% ^qUswWgn+6&xqHN&%');

These are configuration lines that we can paste directly in our configuration file to set secure keys. Copy the output you received now.

Now, open the WordPress configuration file:

  • nano /var/www/html/wp-config.php

Find the section that contains the dummy values for those settings. It will look something like this:

/var/www/html/wp-config.php
. . .

define('AUTH_KEY',         'put your unique phrase here');
define('SECURE_AUTH_KEY',  'put your unique phrase here');
define('LOGGED_IN_KEY',    'put your unique phrase here');
define('NONCE_KEY',        'put your unique phrase here');
define('AUTH_SALT',        'put your unique phrase here');
define('SECURE_AUTH_SALT', 'put your unique phrase here');
define('LOGGED_IN_SALT',   'put your unique phrase here');
define('NONCE_SALT',       'put your unique phrase here');

. . .

Delete those lines and paste in the values you copied from the command line:

/var/www/html/wp-config.php
. . .

define('AUTH_KEY',         'VALUES COPIED FROM THE COMMAND LINE');
define('SECURE_AUTH_KEY',  'VALUES COPIED FROM THE COMMAND LINE');
define('LOGGED_IN_KEY',    'VALUES COPIED FROM THE COMMAND LINE');
define('NONCE_KEY',        'VALUES COPIED FROM THE COMMAND LINE');
define('AUTH_SALT',        'VALUES COPIED FROM THE COMMAND LINE');
define('SECURE_AUTH_SALT', 'VALUES COPIED FROM THE COMMAND LINE');
define('LOGGED_IN_SALT',   'VALUES COPIED FROM THE COMMAND LINE');
define('NONCE_SALT',       'VALUES COPIED FROM THE COMMAND LINE');

. . .

Next, we need to modify some of the database connection settings at the beginning of the file. You need to adjust the database name, the database user, and the associated password that we configured within MySQL.

The other change we need to make is to set the method that WordPress should use to write to the filesystem. Since we’ve given the web server permission to write where it needs to, we can explicitly set the filesystem method to “direct”. Failure to set this with our current settings would result in WordPress prompting for FTP credentials when we perform some actions.

This setting can be added below the database connection settings, or anywhere else in the file:

/var/www/html/wp-config.php
. . .

define('DB_NAME', 'wordpress');

/** MySQL database username */
define('DB_USER', 'wordpressuser');

/** MySQL database password */
define('DB_PASSWORD', 'password');

. . .

define('FS_METHOD', 'direct');

Save and close the file when you are finished.

Step 6: Complete the Installation Through the Web Interface

Now that the server configuration is complete, we can complete the installation through the web interface.

In your web browser, navigate to your server’s domain name or public IP address:

http://server_domain_or_IP

Select the language you would like to use:

WordPress language selection

Next, you will come to the main setup page.

Select a name for your WordPress site and choose a username (it is recommended not to choose something like “admin” for security purposes). A strong password is generated automatically. Save this password or select an alternative strong password.

Enter your email address and select whether you want to discourage search engines from indexing your site:

WordPress setup installation

When you click ahead, you will be taken to a page that prompts you to log in:

WordPress login prompt

Once you log in, you will be taken to the WordPress administration dashboard:

WordPress login prompt

Upgrading WordPress

As WordPress upgrades become available, you will be unable in install them through the interface with the current permissions.

The permissions we selected here are meant to provide a good balance between security and usability for the 99% of times between upgrading. However, they are a bit too restrictive for the software to automatically apply updates.

When an update becomes available, log back into your server as your sudo user. Temporarily give the web server process access to the whole document root:

  • sudo chown -R www-data /var/www/html

Now, go back the WordPress administration panel and apply the update.

When you are finished, lock the permissions down again for security:

  • sudo chown -R sammy /var/www/html

This should only be necessary when applying upgrades to WordPress itself.

Conclusion

WordPress should be installed and ready to use! Some common next steps are to choose the permalinks setting for your posts (can be found in Settings > Permalinks) or to select a new theme (in Appearance > Themes). If this is your first time using WordPress, explore the interface a bit to get acquainted with your new CMS.

reposted from DigitalOcean

Remove a directory and all its contents in Linux

When attempting to remove a directory using a command such as the rmdir command, you may receive a prompt such as “rmdir: ‘dir’: Directory not empty” and be unable to delete the directory.

To remove a directory that contains other files or directories, use the following command.

rm -r mydir

In the example above, you would replace “mydir” with the name of the directory you want to delete. For example, if the directory was named “files”, you would type rm -r files at the prompt.

Executing the above command would delete all files and directories within the directory named in the command. However, it would also present a prompt for approval to delete each of the files. If you don’t want to receive a prompt for each file, use the following command instead.

rm -rf mydir

In the above example, the “mydir” directory, along with all files and directories within that directory, would be deleted with no prompt or message.

Run a node.js app as a background service

Make a myapp.service file (replacing ‘myapp’ with your app’s name, obviously):

[Unit]
Description=My app

[Service]
ExecStart=/var/www/myapp/app.js
Restart=always
User=nobody
# Note RHEL/Fedora uses 'nobody', Debian/Ubuntu uses 'nogroup'
Group=nobody  
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/var/www/myapp

[Install]
WantedBy=multi-user.target

Note if you’re new to Unix: /var/www/myapp/app.js should have #!/usr/bin/env node on the very first line.

Copy your service file into the /etc/systemd/system.

Start it with systemctl start myapp.

Enable it to run on boot with systemctl enable myapp.

See logs with journalctl -u myapp

This is taken from How we deploy node apps on Linux, 2018 edition, which also includes commands to generate an AWS/DigitalOcean/Azure CloudConfig to build Linux/node servers (including the .service file).

Ubuntu部署Parse Server (关键: 安装nginx)

前提条件:
Ubuntu Server 16.04.1 LTS 64 服务器
一个域名

  1. 登陆Ubuntu 服务器,除了root或者安装的用户之外,创建一个管理员用户:
//创建用户
sudo adduser xxxxxx

//授权管理员权限
sudo usermod -aG sudo xxxxxx

参考连接:Initial Server Setup with Ubuntu 16.04

  1. 安装Node和npm
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -

sudo apt-get install -y nodejs

//安装完毕后可以用下面的命令查看node和npm的版本
node --version
npm --version

参考连接:Installing Node.js via package manager

  1. 安装mongo db
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5
echo "deb [ arch=amd64,arm64 ] 

https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list

sudo apt-get update

sudo apt-get install -y mongodb-org

参考连接:Install MongoDB Community Edition on Ubuntu

系统重启时,自动启动mongodb

sudo systemctl enable mongod
  1. 安装Nginx
sudo apt-get update
sudo apt-get install nginx

//安装完毕之后,Nginx会自动启动
//可以在浏览器查看ip,得到的应该如下:
//不知道ip的话,可以用下面的命令得到
ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'
image.png

参考连接:How To Install Nginx on Ubuntu 14.04 LTS

  1. 设置Let’s Encrypt支持https
    5.1 添加云解析:
    在购买的云服务器的控制台,找到云解析,找到购买的域名,添加两条解析:
    — 添加一条A record,将域名”example.com”指向Ubuntu服务器的公网IP
    — 添加一条A record,将域名”www.example.com“指向Ubuntu服务器的公网IP
    5.2 安装Certbot
sudo add-apt-repository ppa:certbot/certbot

sudo apt-get update

sudo apt-get install python-certbot-nginx

配置Nginx

sudo nano /etc/nginx/sites-available/default

将server_name _;这一行的内容修改为对应的域名,例如:

server_name example.com www.example.com;

//检查修改内容是否正确
sudo nginx -t

//重启nginx
sudo service nginx reload

获取SSL证书

//记得修改对应的域名
sudo certbot --nginx -d example.com -d www.example.com

自动续约SSL证书

sudo certbot renew --dry-run

参考连接:How To Secure Nginx with Let’s Encrypt on Ubuntu 14.04

配置Mongo DB支持SSL连接

sudo cat /etc/letsencrypt/archive/domain_name/{fullchain1.pem,privkey1.pem} | sudo tee /etc/ssl/mongo.pem

//确保mongo.pem 只可以被 mongodb 访问
sudo chown mongodb:mongodb /etc/ssl/mongo.pem
sudo chmod 600 /etc/ssl/mongo.pem

修改mongo配置文件

sudo nano /etc/mongod.conf

//修改内容如下:
# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0
  ssl:
    mode: requireSSL
    PEMKeyFile: /etc/ssl/mongo.pem

# security
security:
  authorization: enabled

setParameter:
  failIndexKeyTooLong: false

保存配置文件

添加一个新的DB管理员用户

//连接mongo db
mongo --port 27017

//创建一个管理员用户(请修改为自己的用户名和密码)
use admin
db.createUser({
  user: "sammy",
  pwd: "password",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
exit

重启mongo db

sudo service mongod restart

以后可以这样连接mongo db

//然后需要输入密码
mongo --port 27017 --ssl --sslAllowInvalidCertificates --authenticationDatabase admin --username sammy --password

创建一个database和对应的db用户

use database_name
db.createUser({ user: "database_user", pwd: "password", roles: [ "readWrite", "dbAdmin" ] })

//注意,上面的”sammy”是DB登陆用户,而这个”database_user”才可以对这个database可以操作。我们后面连接数据库时,需要用到这个”database_user”和对应的密码以及数据库。

例如:

mongodb://database_user:password@your_domain_name:27017/database_name?ssl=true

安装Parse Server App Sample

git clone https://github.com/ParsePlatform/parse-server-example.git

cd ~/parse-server-example

npm install

测试Sample Application

npm start

结果如下:
> parse-server-example@1.0.0 start /home/sammy/parse-server-example
> node index.js

DATABASE_URI not specified, falling back to localhost.
parse-server-example running on port 1337.

另外开启一个session连接服务器,用如下测试

curl -X POST \
  -H "X-Parse-Application-Id: myAppId" \
  -H "Content-Type: application/json" \
  -d '{"score":1337,"playerName":"Sammy","cheatMode":false}' \
  http://localhost:1337/parse/classes/GameScore

Output
{"objectId":"fu7t4oWLuW","createdAt":"2016-02-02T18:43:00.659Z"}

curl -H "X-Parse-Application-Id: myAppId" http://localhost:1337/parse/classes/GameScore

Output
{"results":[{"objectId":"GWuEydYCcd","score":1337,"playerName":"Sammy","cheatMode":false,"updatedAt":"2016-02-02T04:04:29.497Z","createdAt":"2016-02-02T04:04:29.497Z"}]}

curl -X POST \
  -H "X-Parse-Application-Id: myAppId" \
  -H "Content-Type: application/json" \
  -d '{}' \
  http://localhost:1337/parse/functions/hello

Output
{"result":"Hi"}

回到原来的Session,Ctrl-C终止Parse Application的运行。

安装dashboard

cd ~

npm install -g parse-dashboard

//将dashboard加入package中
cd ~/parse-server-example

nano package.json
"dependencies"中添加一行
parse-dashboard": "1.1.2" 

npm install

配置新的Application,包括dashboard

nano my_app.js

内容如下:

// Packtor Server
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var ParseDashboard = require('parse-dashboard');
var path = require('path');

var databaseUri = process.env.DATABASE_URI || 'mongodb://database_user:password@your_domain_name:27017/database_name?ssl=tru';

if (!databaseUri) {
  console.log('DATABASE_URI not specified, falling back to localhost.');
}

// Set up parse server
var api = new ParseServer({
  databaseURI: databaseUri || 'mongodb://database_user:password@your_domain_name:27017/database_name?ssl=tru',
  cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
  appId: process.env.APP_ID || 'appId',
  masterKey: process.env.MASTER_KEY || 'masterKey',
  serverURL: process.env.SERVER_URL || 'http://localhost:1337/parse',
  publicServerURL: 'https://your_domain_name/parse'
});

var app = express();

// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));

// Serve the Parse API on the /parse URL prefix
var mountPath = process.env.PARSE_MOUNT || '/parse';
app.use(mountPath, api);

// Parse Server plays nicely with the rest of your web routes
app.get('/', function(req, res) {
  res.status(200).send('Parse Server App');
});

var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
    console.log('Parse-server running on port ' + port + '.');
});

// Set up parse dashboard
var dashboard = new ParseDashboard({
  "apps": [{
      "serverURL": 'https://your_domain_name/parse', // Not localhost
      "appId": 'appId',
      "masterKey": 'masterKey',
      "appName": "appName",
      "production": false,
      "iconName": "app-icon.png",
  }],
  "users": [
    {
      "user":"user",
      "pass":"password"
    }
  ],
  "iconsFolder": "icons"
});

var dashApp = express();

// make the Parse Dashboard available at /dashboard
dashApp.use('/dashboard', dashboard);

// Parse Server plays nicely with the rest of your web routes
dashApp.get('/', function(req, res) {
  res.status(200).send('Parse Dashboard App');
});

var httpServerDash = require('http').createServer(dashApp);
httpServerDash.listen(4040, function() {
    console.log('dashboard-server running on port 4040.');
});

运行这个Application,可以用如下命令:

node my_app.js

结果应该如下:
Iconsfolder at path: icons not found!
Parse-server running on port 1337.
dashboard-server running on port 4040.

配置Nignx

Ctrl+C终止Application运行

sudo nano /etc/nginx/sites-available/default

在location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }
之后, 添加如下内容
        location /parse/ {
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-NginX-Proxy true;
                proxy_pass http://localhost:1337/parse/;
                proxy_ssl_session_reuse off;
                proxy_set_header Host $http_host;
                proxy_redirect off;
        }

        # Pass requests for /dashboard/ to Parse Server instance at localhost:4040
        location /dashboard/ {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-NginX-Proxy true;
            proxy_pass http://localhost:4040/dashboard/;
            proxy_ssl_session_reuse off;
            proxy_set_header Host $http_host;
            proxy_redirect off;
        }

保存,退出,并重启Nginx

sudo nginx -t

sudo service nginx reload

再次运行Application

node my_app.js

此时,访问https://www.iosreader.com/dashboard/将会跳转到dashboard的login界面,可以用定义在配置文件里的用户名(user)和密码(password)进行登陆

安装PM2

Ctrl+c退出Application

//返回用户目录
cd ~
sudo npm install -g pm2

/*
配置ecosystem.json

nano ecosystem.json
{
  "apps" : [{
    "name"        : "parse-wrapper",
    "script"      : "/home/xxxxxx/parse-server-example/my_app.js",
    "watch"       : true,
    "merge_logs"  : true,
    "cwd"         : "/home/xxxxxx/parse-server-example",
    "env": {
      "PARSE_SERVER_CLOUD_CODE_MAIN": "/home/xxxxxx/parse-server-example/cloud/main.js",
      "PARSE_SERVER_DATABASE_URI": "mongodb://database_user:password@your_domain_name:27017/database_name?ssl=tru';
e",
      "PARSE_SERVER_APPLICATION_ID": "appId",
      "PARSE_SERVER_MASTER_KEY": "masterKey",
    }
  }]
}

*/

运行PM2

//pm2 start ecosystem.json
修改为pm2 start my_app.js 
不知道为何,配置ecosystem.json并且通过该文件启动my_app.js,在服务器重启之后,parse server的连接会出错,暂时不清楚问题的原因,以及如何修改。但是可以通过直接启动my_app.js,此方法在服务器重启之后,一切服务正常。

Sample Output
...
[PM2] Spawning PM2 daemon
[PM2] PM2 Successfully daemonized
[PM2] Process launched
┌───────────────┬────┬──────┬──────┬────────┬─────────┬────────┬─────────────┬──────────┐
│ App name      │ id │ mode │ pid  │ status │ restart │ uptime │ memory      │ watching │
├───────────────┼────┼──────┼──────┼────────┼─────────┼────────┼─────────────┼──────────┤
│ parse-wrapper │ 0  │ fork │ 3499 │ online │ 00s     │ 13.680 MB   │  enabled │
└───────────────┴────┴──────┴──────┴────────┴─────────┴────────┴─────────────┴──────────┘
 Use `pm2 show <id|name>` to get more details about an app

保存

pm2 save

Sample Output
[PM2] Dumping processes
sudo pm2 startup ubuntu -u xxxxxx --hp /home/xxxxxx/

republished from: https://www.jianshu.com/p/fde2039344ab

How to Install and Configure MongoDB on Ubuntu

MongoDB is a NoSQL database that offers a high performance, high availability, and automatic scaling enterprise database. MongoDB is a NoSQL database, so you can’t use SQL (Structured Query Language) to insert and retrieve data, and it does not store data in tables like MySQL or Postgres. Data is stored in a “document” structure in JSON format (in MongoDB called BSON). MongoDB was first introduced in 2009 and is currently developed by the company MongoDB Inc.

MongoDB only provides packages for 64-bit LTS (long-term support) Ubuntu releases. For example, 14.04 LTS (trusty), 16.04 LTS (xenial), 18.04 LTS (bionic) and so on.

In this tutorial, I will install MongoDB 3.6 on Ubuntu 18.04 LTS.

Prerequisites

  • Ubuntu Server 18.04 – 64 bit
  • Root privileges

What we will do in this tutorial:

  1. Install MongoDB
  2. Configure MongoDB
  3. Conclusion

Install MongoDB on Ubuntu 18.04

Step 1 – Importing the Public Key

GPG keys of the software distributor are required by the Ubuntu package manager apt (Advanced Package Tool) to ensure package consistency and authenticity. Run this command to import MongoDB keys to your server.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5

Step 2 – Create source list file MongoDB

Create a MongoDB list file in /etc/apt/sources.list.d/ with this command:

echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list

MongoDB has not released packages for Bionic Beaver yet, but the Xenial packages are working fine on Ubuntu 18.04 LTS. You might check out the URL http://repo.mongodb.org/apt/ubuntu/dists/ though before you execute the above command. If you see a directory ‘bionic’ on that web page, then replace the word ‘xenial’ in the above command with the word ‘bionic’.

Step 3 – Update the repository

update the repository with the apt command:

sudo apt-get update

Step 4 – Install MongoDB

Now you can install MongoDB by typing this command:

sudo apt-get install -y mongodb-org

The MongoDB apt installer created a mongod.service file for Systemd automatically, so there is no need to create it manually anymore.

Start MongoDB and add it as a service to be started at boot time:

systemctl start mongod
systemctl enable mongod

Now check that MongoDB has been started on port 27017 with the netstat command.

netstat -plntu

Check if MongoDB is running.

Configure MongoDB username and password

When the MongoDB packages are installed you can configure username and password for the database server:

Step 1 – Open mongo shell

Before you set up a username and password for MongoDB, you need to open the MongoDB shell on your server. You can login by typing:

mongo

If you get error Failed global initialization: BadValue Invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are set correctly, try the command:

export LC_ALL=C
mongo

Step 2 – Switch to the database admin

Once you`re in the MongoDB shell, switch to the database named admin:

use admin

Step 3 – Create the root user

Create the root user with this command :

db.createUser({user:"admin", pwd:"admin123", roles:[{role:"root", db:"admin"}]})

Desc: Create user admin with password admin123 and have the permission/role as root and the database is admin.

Create a admin user in MongoDB

Now type exit to exit from MongoDB shell.

Step 4 – Enable mongodb authentication

Edit the mongodb service file ‘/lib/systemd/system/mongod.service’ with your editor.

nano /lib/systemd/system/mongod.service

On the ‘ExecStart‘ line 9, add the new option ‘–auth‘.

ExecStart=/usr/bin/mongod –auth –config /etc/mongod.conf

Save the service file and exit nano.

Reload the systemd service:

systemctl daemon-reload

Step 5 – Restart MongoDB and try to connect

Now restart MongoDB and connect with the user created.

sudo service mongod restart

and connect to the MongoDB shell with this command:

mongo -u admin -p admin123 --authenticationDatabase admin

and you will see the output like this:

Test MongoDB Authentication.

Virtual Machine image

This tutorial is available as ready to use virtual machine in OVA / OVF format for Howtoforge subscribers. The VM format is compatible with VMWare and Virtualbox and other tools that can import the ova or ovf format. You can find the download link in the right menu on the top. Click on the filename to start the download.

The login details of the VM are:

SSH Login

Username: administrator
Password: howtoforge

The administrator user has sudo permissions.

Please change the passwords after the first boot.

The VM is configured for the static IP 192.168.1.100. Instructions on how to change the static IP can be found here.

Conclusion

A well-known NoSQL database that offers high performance, high availability, and automatic scaling is MongoDB. It is different from the RDBMS such as MySQL, PostgreSQL, and SQLite as it does not use SQL to set and retrieve data. MongoDB stores data in `documents` called BSON (binary representation of JSON with additional types of information). MongoDB is only available for 64-bit Long Term Support Ubuntu Release.

How To Run Parse Server on Ubuntu

Introduction

Parse is a Mobile Backend as a Service platform, owned by Facebook since 2013. In January of 2016, Parse announced that its hosted services would shut down in January of 2017.

In order to help its users transition away from the service, Parse has released an open source version of its backend, called Parse Server, which can be deployed to environments running Node.js and MongoDB.

This guide supplements the official documentation with detailed instructions for installing Parse Server on an Ubuntu 14.04 system, such as a DigitalOcean Droplet. It is intended first and foremost as a starting point for Parse developers who are considering migrating their applications, and should be read in conjunction with the official Parse Server Guide.

Prerequisites

$ sudo apt-get install build-essential git python-software-properties

This guide assumes that you have a clean Ubuntu 14.04 system, configured with a non-root user with sudo privileges for administrative tasks. You may wish to review the guides in the New Ubuntu 14.04 Server Checklist series.

Additionally, your system will need a running instance of MongoDB. You can start by working through How to Install MongoDB on Ubuntu 14.04. MongoDB can also be installed automatically on a new Droplet by adding this script to its User Data when creating it. Check out this tutorial to learn more about Droplet User Data.

Once your system is configured with a sudo user and MongoDB, return to this guide and continue.

Step 1 — Install Node.js and Development Tools

Begin by changing the current working path to your sudo user’s home directory:

  • cd ~

NodeSource offers an Apt repository for Debian and Ubuntu Node.js packages. We’ll use it to install Node.js. NodeSource offers an installation script for the the latest stable release (v5.5.0 at the time of this writing), which can be found in the installation instructions. Download the script with curl:

  • curl -sL https://deb.nodesource.com/setup_5.x -o nodesource_setup.sh

You can review the contents of this script by opening it with nano, or your text editor of choice:

  • nano ./nodesource_setup.sh

Next, run nodesource_setup.sh. The -E option to sudo tells it to preserve the user’s environment variables so that they can be accessed by the script:

  • sudo -E bash ./nodesource_setup.sh

Once the script has finished, NodeSource repositories should be available on the system. We can use apt-get to install the nodejs package. We’ll also install the build-essential metapackage, which provides a range of development tools that may be useful later, and the Git version control system for retrieving projects from GitHub:

  • sudo apt-get install -y nodejs build-essential git

Step 2 — Install an Example Parse Server App

Parse Server is designed to be used in conjunction with Express, a popular web application framework for Node.js which allows middleware components conforming to a defined API to be mounted on a given path. The parse-server-example repository contains a stubbed-out example implementation of this pattern.

Retrieve the repository with git:

  • git clone https://github.com/ParsePlatform/parse-server-example.git

Enter the parse-server-example directory you just cloned:

  • cd ~/parse-server-example

Use npm to install dependencies, including parse-server, in the current directory:

  • npm install

npm will fetch all of the modules required by parse-server and store them in ~/parse-server-example/node_modules.

Step 3 — Test the Sample Application

Use npm to start the service. This will run a command defined in the start property of package.json. In this case, it runs node index.js:

  • npm start
Output
> parse-server-example@1.0.0 start /home/sammy/parse-server-example
> node index.js

DATABASE_URI not specified, falling back to localhost.
parse-server-example running on port 1337.

You can terminate the running application at any time by pressing Ctrl-C.

The Express app defined in index.js will pass HTTP requests on to the parse-server module, which in turn communicates with your MongoDB instance and invokes functions defined in ~/parse-server-example/cloud/main.js.

In this case, the endpoint for Parse Server API calls defaults to:

http://your_server_IP/parse

In another terminal, you can use curl to test this endpoint. Make sure you’re logged into your server first, since these commands reference localhost instead of a specific IP address.

Create a record by sending a POST request with an X-Parse-Application-Id header to identify the application, along with some data formatted as JSON:

curl -X POST \
  -H "X-Parse-Application-Id: myAppId" \
  -H "Content-Type: application/json" \
  -d '{"score":1337,"playerName":"Sammy","cheatMode":false}' \
  http://localhost:1337/parse/classes/GameScore
Output
{"objectId":"fu7t4oWLuW","createdAt":"2016-02-02T18:43:00.659Z"}

The data you sent is stored in MongoDB, and can be retrieved by using curl to send a GET request:

  • curl -H “X-Parse-Application-Id: myAppId” http://localhost:1337/parse/classes/GameScore
Output
{"results":[{"objectId":"GWuEydYCcd","score":1337,"playerName":"Sammy","cheatMode":false,"updatedAt":"2016-02-02T04:04:29.497Z","createdAt":"2016-02-02T04:04:29.497Z"}]}

Run a function defined in ~/parse-server-example/cloud/main.js:

curl -X POST \
  -H "X-Parse-Application-Id: myAppId" \
  -H "Content-Type: application/json" \
  -d '{}' \
  http://localhost:1337/parse/functions/hello
Output
{"result":"Hi"}

Step 4 — Configure Sample Application

In your original terminal, press Ctrl-C to stop the running version of the Parse Server application.

As written, the sample script can be configured by the use of six environment variables:

Variable Description
DATABASE_URI A MongoDB connection URI, like mongodb://localhost:27017/dev
CLOUD_CODE_MAIN A path to a file containing Parse Cloud Code functions, like cloud/main.js
APP_ID A string identifier for your app, like myAppId
MASTER_KEY A secret master key which allows you to bypass all of the app’s security mechanisms
PARSE_MOUNT The path where the Parse Server API should be served, like /parse
PORT The port the app should listen on, like 1337

You can set any of these values before running the script with the export command. For example:

  • export APP_ID=fooApp

It’s worth reading through the contents of index.js, but in order to get a clearer picture of what’s going on, you can also write your own shorter version of the example . Open a new script in your editor:

  • nano my_app.js

And paste the following, changing the highlighted values where desired:

~/parse-server-example/my_app.js
var express = require('express');
var ParseServer = require('parse-server').ParseServer;

// Configure the Parse API
var api = new ParseServer({
  databaseURI: 'mongodb://localhost:27017/dev',
  cloud: __dirname + '/cloud/main.js',
  appId: 'myOtherAppId',
  masterKey: 'myMasterKey'
});

var app = express();

// Serve the Parse API on the /parse URL prefix
app.use('/myparseapp', api);

// Listen for connections on port 1337
var port = 9999;
app.listen(port, function() {
    console.log('parse-server-example running on port ' + port + '.');
});

Exit and save the file, then run it with Node.js:

  • node my_app.js
Output
parse-server-example running on port 9999.

Again, you can press Ctrl-C at any time to stop my_app.js. As written above, the sample my_app.js will behave nearly identically to the provided index.js, except that it will listen on port 9999, with Parse Server mounted at /myparseapp, so that the endpoint URL looks like so:

http://yourserverIP:9999/myparseapp

And it can be tested with curl like so:

  • curl -H “X-Parse-Application-Id: myOtherAppId” http://localhost:9999/myparseapp/classes/GameScore`

Conclusion

You should now know the basics of running a Node.js application like Parse Server in an Ubuntu environment. Fully migrating an app from Parse is likely to be a more involved undertaking, requiring code changes and careful planning of infrastructure.

For much greater detail on this process, see the second guide in this series, How To Migrate a Parse App to Parse Server on Ubuntu 14.04. You should also reference the official Parse Server Guide, particularly the section on migrating an existing Parse app.

republished from https://www.digitalocean.com/

How to Install MongoDB on Ubuntu

Introduction

MongoDB is a free and open-source NoSQL document database used commonly in modern web applications. This tutorial will help you set up MongoDB on your server for a production application environment.

Prerequisites

To follow this tutorial, you will need:

Step 1 — Adding the MongoDB Repository

MongoDB is already included in Ubuntu package repositories, but the official MongoDB repository provides most up-to-date version and is the recommended way of installing the software. In this step, we will add this official repository to our server.

Ubuntu ensures the authenticity of software packages by verifying that they are signed with GPG keys, so we first have to import they key for the official MongoDB repository.

  • sudo apt-key adv –keyserver hkp://keyserver.ubuntu.com:80 –recv EA312927

After successfully importing the key, you will see:

Output
gpg: Total number processed: 1
gpg:               imported: 1  (RSA: 1)

Next, we have to add the MongoDB repository details so apt will know where to download the packages from.

Issue the following command to create a list file for MongoDB.

  • echo “deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse” | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list

After adding the repository details, we need to update the packages list.

  • sudo apt-get update

Step 2 — Installing and Verifying MongoDB

Now we can install the MongoDB package itself.

  • sudo apt-get install -y mongodb-org

This command will install several packages containing latest stable version of MongoDB along with helpful management tools for the MongoDB server.

Next, start MongoDB with systemctl.

  • sudo systemctl start mongod

You can also use systemctl to check that the service has started properly.

  • sudo systemctl status mongod
Output
● mongodb.service - High-performance, schema-free document-oriented database
   Loaded: loaded (/etc/systemd/system/mongodb.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2016-04-25 14:57:20 EDT; 1min 30s ago
 Main PID: 4093 (mongod)
    Tasks: 16 (limit: 512)
   Memory: 47.1M
      CPU: 1.224s
   CGroup: /system.slice/mongodb.service
           └─4093 /usr/bin/mongod --quiet --config /etc/mongod.conf

The last step is to enable automatically starting MongoDB when the system starts.

  • sudo systemctl enable mongod

The MongoDB server is now configured and running, and you can manage the MongoDB service using the systemctl command (e.g. sudo systemctl stop mongodsudo systemctl start mongod).

Step 3 — Adjusting the Firewall (Optional)

Assuming you have followed the initial server setup tutorial instructions to enable the firewall on your server, MongoDB server will be inaccessible from the internet.

If you intend to use the MongoDB server only locally with applications running on the same server, it is a recommended and secure setting. However, if you would like to be able to connect to your MongoDB server from the internet, we have to allow the incoming connections in ufw.

To allow access to MongoDB on its default port 27017 from everywhere, you could use sudo ufw allow 27017. However, enabling internet access to MongoDB server on a default installation gives unrestricted access to the whole database server.

in most cases, MongoDB should be accessed only from certain trusted locations, such as another server hosting an application. To accomplish this task, you can allow access on MongoDB’s default port while specifying the IP address of another server that will be explicitly allowed to connect.

  • sudo ufw allow from your_other_server_ip/32 to any port 27017

You can verify the change in firewall settings with ufw.

  • sudo ufw status

You should see traffic to 27017 port allowed in the output.If you have decided to allow only a certain IP address to connect to MongoDB server, the IP address of the allowed location will be listed instead of Anywhere in the output.

Output
Status: active

To                         Action      From
--                         ------      ----
27017                      ALLOW       Anywhere
OpenSSH                    ALLOW       Anywhere
27017 (v6)                 ALLOW       Anywhere (v6)
OpenSSH (v6)               ALLOW       Anywhere (v6)

More advanced firewall settings for restricting access to services are described in UFW Essentials: Common Firewall Rules and Commands.

Conclusion

You can find more in-depth instructions regarding MongoDB installation and configuration in these DigitalOcean community articles.

Initial Server Setup with Ubuntu

Introduction

When you first create a new Ubuntu 16.04 server, there are a few configuration steps that you should take early on as part of the basic setup. This will increase the security and usability of your server and will give you a solid foundation for subsequent actions.

Step One — Root Login

To log into your server, you will need to know your server’s public IP address. You will also need the password or, if you installed an SSH key for authentication, the private key for the “root” user’s account. If you have not already logged into your server, you may want to follow the first tutorial in this series, How to Connect to Your Droplet with SSH, which covers this process in detail.

If you are not already connected to your server, go ahead and log in as the root user using the following command (substitute the highlighted word with your server’s public IP address):

  • ssh root@your_server_ip

Complete the login process by accepting the warning about host authenticity, if it appears, then providing your root authentication (password or private key). If it is your first time logging into the server with a password, you will also be prompted to change the root password.

About Root

The root user is the administrative user in a Linux environment that has very broad privileges. Because of the heightened privileges of the root account, you are actually discouraged from using it on a regular basis. This is because part of the power inherent with the root account is the ability to make very destructive changes, even by accident.

The next step is to set up an alternative user account with a reduced scope of influence for day-to-day work. We’ll teach you how to gain increased privileges during the times when you need them.

Step Two — Create a New User

Once you are logged in as root, we’re prepared to add the new user account that we will use to log in from now on.

This example creates a new user called “sammy”, but you should replace it with a username that you like:

  • adduser sammy

You will be asked a few questions, starting with the account password.

Enter a strong password and, optionally, fill in any of the additional information if you would like. This is not required and you can just hit ENTER in any field you wish to skip.

Step Three — Root Privileges

Now, we have a new user account with regular account privileges. However, we may sometimes need to do administrative tasks.

To avoid having to log out of our normal user and log back in as the root account, we can set up what is known as “superuser” or root privileges for our normal account. This will allow our normal user to run commands with administrative privileges by putting the word sudo before each command.

To add these privileges to our new user, we need to add the new user to the “sudo” group. By default, on Ubuntu 16.04, users who belong to the “sudo” group are allowed to use the sudo command.

As root, run this command to add your new user to the sudo group (substitute the highlighted word with your new user):

  • usermod -aG sudo sammy

Now your user can run commands with superuser privileges! For more information about how this works, check out this sudoers tutorial.

If you want to increase the security of your server, follow the rest of the steps in this tutorial.

The next step in securing your server is to set up public key authentication for your new user. Setting this up will increase the security of your server by requiring a private SSH key to log in.

Generate a Key Pair

If you do not already have an SSH key pair, which consists of a public and private key, you need to generate one. If you already have a key that you want to use, skip to the Copy the Public Key step.

To generate a new key pair, enter the following command at the terminal of your local machine (ie. your computer):

  • ssh-keygen

Assuming your local user is called “localuser”, you will see output that looks like the following:

ssh-keygen output
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/localuser/.ssh/id_rsa):

Hit return to accept this file name and path (or enter a new name).

Next, you will be prompted for a passphrase to secure the key with. You may either enter a passphrase or leave the passphrase blank.

Note: If you leave the passphrase blank, you will be able to use the private key for authentication without entering a passphrase. If you enter a passphrase, you will need both the private key and the passphrase to log in. Securing your keys with passphrases is more secure, but both methods have their uses and are more secure than basic password authentication.

This generates a private key, id_rsa, and a public key, id_rsa.pub, in the .ssh directory of the localuser‘s home directory. Remember that the private key should not be shared with anyone who should not have access to your servers!

Copy the Public Key

After generating an SSH key pair, you will want to copy your public key to your new server. We will cover two easy ways to do this.

Note: The ssh-copy-id method will not work on DigitalOcean if an SSH key was selected during Droplet creation. This is because DigitalOcean disables password authentication if an SSH key is present, and the ssh-copy-id relies on password authentication to copy the key.

If you are using DigitalOcean and selected an SSH key during Droplet creation, use option 2 instead.

Option 1: Use ssh-copy-id

If your local machine has the ssh-copy-id script installed, you can use it to install your public key to any user that you have login credentials for.

Run the ssh-copy-id script by specifying the user and IP address of the server that you want to install the key on, like this:

  • ssh-copy-id sammy@your_server_ip

After providing your password at the prompt, your public key will be added to the remote user’s .ssh/authorized_keys file. The corresponding private key can now be used to log into the server.

Option 2: Manually Install the Key

Assuming you generated an SSH key pair using the previous step, use the following command at the terminal of your local machine to print your public key (id_rsa.pub):

  • cat ~/.ssh/id_rsa.pub

This should print your public SSH key, which should look something like the following:

id_rsa.pub contents
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDBGTO0tsVejssuaYR5R3Y/i73SppJAhme1dH7W2c47d4gOqB4izP0+fRLfvbz/tnXFz4iOP/H6eCV05hqUhF+KYRxt9Y8tVMrpDZR2l75o6+xSbUOMu6xN+uVF0T9XzKcxmzTmnV7Na5up3QM3DoSRYX/EP3utr2+zAqpJIfKPLdA74w7g56oYWI9blpnpzxkEd3edVJOivUkpZ4JoenWManvIaSdMTJXMy3MtlQhva+j9CgguyVbUkdzK9KKEuah+pFZvaugtebsU+bllPTB0nlXGIJk98Ie9ZtxuY3nCKneB+KjKiXrAvXUPCI9mWkYS/1rggpFmu3HbXBnWSUdf localuser@machine.local

Select the public key, and copy it to your clipboard.

To enable the use of SSH key to authenticate as the new remote user, you must add the public key to a special file in the user’s home directory.

On the server, as the root user, enter the following command to temporarily switch to the new user (substitute your own user name):

  • su – sammy

Now you will be in your new user’s home directory.

Create a new directory called .ssh and restrict its permissions with the following commands:

  • mkdir ~/.ssh
  • chmod 700 ~/.ssh

Now open a file in .ssh called authorized_keys with a text editor. We will use nano to edit the file:

  • nano ~/.ssh/authorized_keys

Now insert your public key (which should be in your clipboard) by pasting it into the editor.

Hit CTRL-x to exit the file, then y to save the changes that you made, then ENTER to confirm the file name.

Now restrict the permissions of the authorized_keys file with this command:

  • chmod 600 ~/.ssh/authorized_keys

Type this command once to return to the root user:

  • exit

Now your public key is installed, and you can use SSH keys to log in as your user.

To read more about how key authentication works, read this tutorial: How To Configure SSH Key-Based Authentication on a Linux Server.

Next, we’ll show you how to increase your server’s security by disabling password authentication.

Now that your new user can use SSH keys to log in, you can increase your server’s security by disabling password-only authentication. Doing so will restrict SSH access to your server to public key authentication only. That is, the only way to log in to your server (aside from the console) is to possess the private key that pairs with the public key that was installed.

Note: Only disable password authentication if you installed a public key to your user as recommended in the previous section, step four. Otherwise, you will lock yourself out of your server!

To disable password authentication on your server, follow these steps.

As root or your new sudo user, open the SSH daemon configuration:

  • sudo nano /etc/ssh/sshd_config

Find the line that specifies PasswordAuthentication, uncomment it by deleting the preceding #, then change its value to “no”. It should look like this after you have made the change:

sshd_config — Disable password authentication
PasswordAuthentication no

Here are two other settings that are important for key-only authentication and are set by default. If you haven’t modified this file before, you do not need to change these settings:

sshd_config — Important defaults
PubkeyAuthentication yes
ChallengeResponseAuthentication no

When you are finished making your changes, save and close the file using the method we went over earlier (CTRL-X, then Y, then ENTER).

Type this to reload the SSH daemon:

  • sudo systemctl reload sshd

Password authentication is now disabled. Your server is now only accessible with SSH key authentication.

Step Six — Test Log In

Now, before you log out of the server, you should test your new configuration. Do not disconnect until you confirm that you can successfully log in via SSH.

In a new terminal on your local machine, log in to your server using the new account that we created. To do so, use this command (substitute your username and server IP address):

  • ssh sammy@your_server_ip

If you added public key authentication to your user, as described in steps four and five, your private key will be used as authentication. Otherwise, you will be prompted for your user’s password.

Note about key authentication: If you created your key pair with a passphrase, you will be prompted to enter the passphrase for your key. Otherwise, if your key pair is passphrase-less, you should be logged in to your server without a password.

Once authentication is provided to the server, you will be logged in as your new user.

Remember, if you need to run a command with root privileges, type “sudo” before it like this:

  • sudo command_to_run

Step Seven — Set Up a Basic Firewall

Ubuntu 16.04 servers can use the UFW firewall to make sure only connections to certain services are allowed. We can set up a basic firewall very easily using this application.

Different applications can register their profiles with UFW upon installation. These profiles allow UFW to manage these applications by name. OpenSSH, the service allowing us to connect to our server now, has a profile registered with UFW.

You can see this by typing:

  • sudo ufw app list
Output
Available applications:
  OpenSSH

We need to make sure that the firewall allows SSH connections so that we can log back in next time. We can allow these connections by typing:

  • sudo ufw allow OpenSSH

Afterwards, we can enable the firewall by typing:

  • sudo ufw enable

Type “y” and press ENTER to proceed. You can see that SSH connections are still allowed by typing:

  • sudo ufw status
Output
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
OpenSSH (v6)               ALLOW       Anywhere (v6)

If you install and configure additional services, you will need to adjust the firewall settings to allow acceptable traffic in. You can learn some common UFW operations in this guide.

republished from https://www.digitalocean.com/