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/

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/