Tutorial

Initial Server Setup with Ubuntu 16.04

Initial Server Setup with Ubuntu 16.04
Not using Ubuntu 16.04?Choose a different version or distribution.
Ubuntu 16.04

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):

  1. 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:

  1. 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):

  1. 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):

  1. 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:

  1. 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):

  1. 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):

  1. 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:

  1. mkdir ~/.ssh
  2. chmod 700 ~/.ssh

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

  1. 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:

  1. chmod 600 ~/.ssh/authorized_keys

Type this command once to return to the root user:

  1. 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:

  1. 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:

  1. 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):

  1. 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:

  1. 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:

  1. 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:

  1. sudo ufw allow OpenSSH

Afterwards, we can enable the firewall by typing:

  1. sudo ufw enable

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

  1. 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.

Where To Go From Here?

At this point, you have a solid foundation for your server. You can install any of the software you need on your server now.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
79 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Hello!

Is there any particular reason that this guide doesn’t recommend the installation of ntp and the configuration of swap space the way that the Initial Server Setup with Ubuntu 14.04 guide did?

Thanks!

I don’t find any reason not to use ntp or swap. Either the writer has forgotten OR (most likely) there will be another article for those things.

DO no longer recommend creating SWAP, that it wears the machine

Why DO not recommend use SWAP? If you have a Droplet with 512MB of RAM it can be usefull or am i wrong?

Hi @zeokat,

SSDs are 20 to 25x slower than RAM.

When the system needs to use swap intensively, it will work slower.

Best,

Fernando Pimenta

I was wondering the same thing.

This comment has been deleted

    Do not change the default SSH port in /etc/ssh/sshd_config like it was mentioned in the previous Ubuntu tutorials. If you do that and enable ufw app OpenSSH, you will lock yourself out of the VPS.

    Or allow the port that you put in the /etc/ssh/sshd_config for more security

    Not security, obscurity.

    FYI: All the characters of your password are on my keyboard. IMHO, password security is only obscurity.

    What is your vision?

    http://manpages.ubuntu.com/manpages/xenial/man8/ufw.8.html

    ufw supports connection rate limiting, which is useful for protecting against brute-force login attacks. When a limit rule is used, ufw will normally allow the connection but will deny connections if an IP address attempts to initiate 6 or more connections within 30 seconds. See http://www.debian-administration.org/articles/187 for details.

    Typical usage is:

         ufw limit ssh/tcp
    

    This comment has been deleted

      This comment has been deleted

        Would it be good to suggest users disable root login via SSH as described in Step Five — Configure SSH Daemon?

        https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-14-04

        Also wondering this @manicas

        Yes, it would be, but it’s mostly up to you.

        In reality, you should never have to log in as root. Ubuntu for desktop has root disabled/inaccessible for this reason.

        I agree. This is the only quibble I have with the tutorial.

        Thanks for the nice article. Just a quick note I thought could be helpful:

        I would disable root login from sshd_config file. This would make tracking easier since everything would be recorded in the system log when sudo is used. If you needed to fall back to root, you still could do so using sudo sulogin command.

        Disabling Root Login

        Type the following command to edit the sshd_config file.

        sudo vim /etc/ssh/sshd_config
        

        Find the following line

        PermitRootLogin yes
        

        Change it to no

        PermitRootLogin no
        

        Save and quit VIM.

        Restart the SSH daemon:

        sudo service sshd restart
        

        Done!

        Now you won’t be able to login using root. If you need root privileges use the sudo command as described above in this article. However, if it ever becomes necessary to fall back to the root user, you can do so issuing the following command:

        sudo sulogin
        

        Footnote: If you are not familiar with VIM, you can use nano or use the following article on VIM. https://www.digitalocean.com/community/tutorials/installing-and-using-the-vim-text-editor-on-a-cloud-server#modal-editing

        I would have included Fail2ban

        sudo apt install fail2ban -y

        your gonna get hammered by brute force attacks on your ssh port anyway why not make them waste time.

        Great tutorial, much appreciated.

        I’m having an issue when I enable ufw. I’m locking myself down :-(

        andy@SVR015:~$ sudo ufw app list Available applications: OpenSSH mosh andy@SVR015:~$ sudo ufw allow OpenSSH Rules updated Rules updated (v6) andy@SVR015:~$ sudo ufw enable Command may disrupt existing ssh connections. Proceed with operation (y|n)? y

        Then I can not reconnect at all … I tried this 4 times within the last 90 minutes … Never had an issue with Ubuntu 14.04

        Any ideas ?

        In the ssh_config file i’ve set PasswordAuthentication no PermitRootLogin without-password

        When I run the command ssh root/user@SERVER_IP_ADDRESS It asks for the password. I have entered my root password but it says permission denied. And after 3 attempts it says connection closed by host because of Authentication Failure

        I complete this guide and all is ok. The only problem I have is that the second user I create I add him ass su bat when I connect from putty and when I try to execute something with sudo the command line prompt me for a password. (The connection with putty is working correct without need a password)

        I have the same problem. I can login with my new sudo user with the SSH key but when I run the command “sudo nano /etc/ssh/sshd_config” it still asks for password. And my SSH key is password free.

        sudo will always ask for your password (at least the first time you use it in a certain time frame); it’s not about logging in at that point, it’s about authorization to raise your user’s privileges.

        I have the same issue. i do not have a password, so how can i make this work?

        Got it, its the password i created in step 2!

        Hi Mitchell,

        Love your tuts. I ran into trouble where I lock myself out of my droplet. After 2 days of struggling with ssh I finally figured out what was wrong. When you enable the fire wall, you must also add the port. Like so Step 1 sudo ufw enable Step 2 sudo ufw allow 22

        SSH works out of port 22 by default. If you don’t do this you will think you missed a step, delete you droplet and try again. Just to end up back where you started with no solution. If you can just add the second step this will save newbies like me tons of frustration.
        I also include a link to https://help.ubuntu.com/12.04/serverguide/firewall.html. There is a ton of useful info.

        No need to delete the droplet when you get yourself locked. Just go to your Droplets page and click on “More” link of the desired droplet and then click “Access console”.

        Or you can open the droplet by clicking its name from the Droplets listing page, then click “Access” link from the menu on the left and then click “Launch Console”.

        After the console is being launched, enter “root” as a login or the new user that you created earlier, then enter the password for that user.

        You are now logged in to your droplet console.

        I keep getting Permission Denied (publickey). after Step Five. Now can’t login neither root or new user.

        Same here! Luckily I kept my root login alive and rolled back the settings in sshd_config. Any Ideas?

        You need to set the ownership of the .ssh directory and the authorized_keys file to the newly created user, not root.

        Log in as root:

        chown yourusername -R ~/.ssh
        

        If you entered su - yourusername prior to creating the .ssh directory, it will be under yourusername’s ownership already. Make sure to include the dash inbetween.

        Do you use DSA keys? They are denied by default in Ubuntu 16.04 due to security issues. Switch to RSA. See https://blackbricksoftware.com/bit-on-bytes/139-dsa-keys-in-openssh-v7-ubuntu-16-04

        Same here…

        I Figured it out. When we pass the ssh-rsa content, sometimes we skip one “s” in the beginning of the file. Check it. Correct: ssh-rsa … Incorect: sh-rsa … Welcome.

        I’m a bit confused why disabling root login, which was in previous server setups and is a trivial change to add while disabling password logins, was not included.

        Was it intentional? Is there something new in 16.04 that necessitates leaving it? Was it left out unintentionally? If so, with this procedure, which I would normally tell staff to use as is, going to be updated?

        I have the same question.

        However, since it seems we will not be receiving an answer any time soon, I think it is safe to assume that it was simply forgotten about when writing the tutorial, but because disabling/abstracting the ‘root’ user access is common practice across all platforms and systems, we as readers can assume that it is still safe to do so.

        I also have not read anything about ‘root’ user access in 16.04 being necessary. 16.04 is pretty close to 14.04 from what I have read and can understand… so I think disabling ‘root’ user access on your server is still the correct practice. Just make sure you have a new sudo user set up before doing so. :)

        When someone is trying to hack into your server they need 3 things: a users name, your IP and your password. If you have a root user that can still login in then you are giving them one of those 3 for free. If you have created a sudo user and blocked the root user from logging in then that is one more thing they have to guess. Because every time the try to log in as root it they will be denied.

        Another reason is that as the root user you have access to everything and thus have the ability to screw up your server. Having a user with sudo privileges you must use the sudo command before altering any sensitive files.

        Ubuntu 14.04 and 16.04 does not really have a root password. It prompts you during installation for a custom user name. It will allow to use sudo and gain root access, but not directly. I find this a really clever and good solution. Although technically it’s possible to set/enable root login it’s not a good idea because of reasons explained by joeklinck.

        I seem to be having trouble with the public key installation. I am able to generate and copy the public key. However, when it comes to installing the key I am able to open the key (nano ~/.ssh/authorized_keys) but not able to save. I hit CTR-x to exit the file, but am not prompted to save the changes. I’m just brought back to the root user prompt. Any ideas what I may be doing wrong?

        The ubuntu PPA package is out of date and I’ve been advised to use certbot which I’ve installed from github.

        sudo apt-get purge --auto-remove letsencrypt
        
        sudo apt update
        sudo apt install git
        
        sudo git clone https://github.com/certbot/certbot /opt/certbot
        sudo ln -s /opt/certbot/certbot-auto /usr/bin/certbot
        
        certbot certonly --webroot -w /var/www/example.com -d example.com -d www.example.com
        

        **Using the webroot plugin means you don’t have to stop apache in order to install or renew the cert. ** That was a problem I ran in to.

        NB: my apache sites were already configured to look in /etc/letsencrypt/live/example/fullchain.pem

        But I had to remove the line from my /etc/apache2/sites-available/default-ssl.conf

        Include /etc/letsencrypt/options-ssl-apache.conf

        since that not longer exists, and trying to include it prevents apache from starting.

        FWIW, there is an unofficial PPA

        I think there is an error on this

        I created my user then exited the droplet and login again, as my new user, using my password, created my .key folder and authorized_keys file, pasted my public key and then:

        chmod 700 ~/.ssh
        chmod 600 ~/.ssh/authorized_keys
        

        but whey i try to login again it kept asking for my password instead of using my keys. It did not worked until i did this:

        sudo chown username -R ~/.ssh
        

        This is pretty unusual. I’m wondering if you forgot the dash between the ‘su’ and ‘username’ in step 5?

        Yes i did. Whats the difference between su username and su - username ?

        As I understand it, leaving off the ‘-’ only gives you the permission level of the user, but putting it in essentially is like logging in (i.e. runs .bash_profile and puts you in their home dir).

        In trying this out, though, I found it actually made no difference, so ignore that remark!

        @manicas The tut should mention that DSA public authentication keys do not work anymore in Ubuntu 16.04 as pointed out in this release note. They are disabled by default by OpenSSH 7.0 and above due to security issues. I spent several hours fighting and figuring out why I could not login to my Ubuntu 16.04 droplet.

        Thanks for the otherwise-great tut!

        Can I login with only key pairs with my sudo user (not root user)? And if yes, how?

        When I created the droplet I connected my previously added keys by checking the checkbox under “Add your SSH keys”. When I logged in as root it worked fine with the added keys. I added a new sudo user, switched to that account and added the public key to the sudo user (password free private key).

        adduser newuser usermod -aG sudo su - newuser mkdir ~/.ssh chmod 700 ~/.ssh nano ~/.ssh/authorized_keys Inserted public key (same key as for root) chmod 600 ~/.ssh/authorized_keys chown newuser -R ~/.ssh

        But when I do the below command: sudo nano /etc/ssh/sshd_config The console now asks for password (the keys are password free).

        What’s wrong??

        SSH authorized keys are doing exactly that. You can open a secure shell without the need to give a password. Running a sudo command will still require you to give the password about every 10 minutes.

        Could anyone point me to a tutorial for hosting multiple sites If I have completed this tutorial with this configuration? Or giving an example of what I should do would also be helpful, thanks!

        Yeah, I forgot to update this comment as I got it working, thanks!

        Hi guys, after i set up all this as described above, I am NOT able anymore to connect to my server with WINSCP and putty, i get error: Disconnected: No supported authentication methods available (server sent: publickey)

        HOW can i fix this? PLEASE HELP I really appreciate it Kind regards Robert

        Shouldn’t the initial step be connecting to the internet? I can’t download anything to get started until I’m connected…

        I have made a bash script to automate the setup process, hopefully this will be useful to someone else.

        Pretty useful. Thanks

        This comment has been deleted

          Hello,

          Thank you for the thorough instruction. I have followed and managed to setup my superuser. However, after succeeding step 6, when I tried to ssh with my root user, it says permission denied. Is that intended or something’s wrong ? Is it meant not to use root unless of emergency?

          I’m new to this. Thanks very much.

          If you do want to use the root account and have unlimited sudo privileges then you can use:

          sudo su
          

          This will usually work and prompt you for your sudo password and then you are root until you logout or exit.

          I can ssh login as root but not as new user, here is what i did:

          adduser newuser
          usermod -aG sudo
          su - newuser
          mkdir ~/.ssh
          chmod 700 ~/.ssh
          nano ~/.ssh/authorizedkeys
          

          Inserted public key (same key as for root)

          chmod 600 ~/.ssh/authorizedkeys
          

          Every step seems to be successful. Why cannot i login as newuser? this happens on both Ubuntu 14 and 16. I am using Putty to generate keys and ssh login.

          Hi jasmineyuan2016,

          The correct file name is authorized_keys and not authorizedkeys (note the underscore character).

          Try again after the creation of the correct file:

          nano ~/.ssh/authorized_keys

          Good luck!

          actually typo, should be authorized_keys. So still doesn’t work. Any other suggestions? or what command i should use to debug ssh error?

          I have done these step over and over and over and I still can’t log in as the user I created. It keeps saying that my password is incorrect when it definitely is not.

          So, I’ve got all of this working, but now I need to get FTP working (so I can upload files to my sparkly, new webserver), BUT, everything I’ve tried, so far, hasn’t worked, and I’m guessing it has to do with the No Password initiative ('cuz the errors always have to do with failed password authentication). How does one do this?!? I even tried using OpenSSL with vsftpd, and the errors were so arcane, whenever I googled them the answers I would hit on were always “Sorry, bud, your server is messed up – contact administration!”

          Hi stlawson,

          You don’t need to use FTP to transfer files. Instead, use a more secure and easy approach: WinSCP.

          Download WinSCP at www.winscp.net.

          Use SCP as a File protocol. To connect, enter your hostname or IP address, username/password.

          Tell me if it helped.

          Hello is there a particular reason, so i get this after following all the guide until step 6?

          ssh: connect to host 192.241.191.42 port 22: Connection refused

          I cant find what i do wrong, please need some help!

          Hi mauriciopayet,

          Connection refused means that the port you are trying to connect to is not actually open. So either you are connecting to the wrong IP address, or to the wrong port, or the server is listening on the wrong port, or is not actually running.

          Please, check:

          -Is yor SSH server running? If not, try: sudo systemctl start sshd -Is your firewall enabled? If so, you must allow ssh on port 22 by running the instructions on step 7 -And, of course, make sure you are connecting using the right IP address for your droplet.

          Best,

          Fernando Pimenta

          Hi thanks for help! I tried the first option and i get wrong password… i am using the password i created previous steps as superuser account… is there anything i should do from here?

          Hello,

          It looks like the port 22 you are trying to SSH through may be closed. This is the default port, so I presume you changed this without changing your firewall settings.

          If you log in to your DigitalOcean account, go to your Droplet and open the ‘console’ you will be able to open port 22 again, or atleast see which port you should be using.

          You could then access your server in Terminal doing something like: ssh -p 22 user@ip-address

          Change the port number {22} and username {user} and IP {ip-address} accordingly.

          I recommend reading the following article (URL below) for guidance, this massively helped me when I was in a similar incident where I was locked out of my own account.

          https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-with-ufw-on-ubuntu-16-04

          Hope this helps

          When i go through Droplet console it asks me for a login, which i should use to access port number info!? really thanks for help!

          Hi @mauriciopayet,

          Just login using the username and the password you set-up for that user. If you didn’t set one up, it’ll be “root” for the username a long with your password.

          Kind regards,

          hi @elliottmangham been working on … i follow all steps in setting up the firewall and allow port 22 but then in mac terminal i try to test log in as step 6 of this guide but it says ssh: connect to host 192.241.191.42 port 22: Connection refused

          Even though i run the command to check port 22 in the console

          why could be this… can i continue setting up the lamp stack?? Please any advice to keep on going is really helpful bro! Thankss thanks thanks

          Hi @mauriciopayet,

          Try logging into ‘Console’ in DigitalOcean in your Droplet, and enter the following:

          sudo ufw allow 22
          

          This will open up the SSH port (22). Then enter the following:

          sudo ufw status numbered
          

          This should list the port settings, and should say port 22 is “ALLOW IN”.

          If so, it should allow you to connect to your server via Terminal. If it continues to refuse access then the issue may be something completely different.

          Perhaps you have disabled password authentication and haven’t yet added your SSH key? Here’s an article that helps you setup SSH keys, though you may have to do in Console if you cannot use SSH in the Terminal: https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys--2

          Hope this helps!

          what if I use this tutorial first?: https://www.digitalocean.com/community/tutorials/how-to-use-ssh-keys-with-putty-on-digitalocean-droplets-windows-users .

          what steps do i need to do in this tutorial if I do that one first? or is there a video tutorial on this guide? i really have no idea what im doing

          I got a trouble with ufw. After setting up, i can’t login to server with my custom login and cert. I disabled ufw and all is ok, but what can i do ? (i work on MacOS Sierra)

          Hello, DO

          I created my new droplet with ssh key and loging in as root was working fine in Putty and Filezilla. I also created a super user and its keys were also all right and working on both terminals. However, this morning when i tried to login as root, the server responded:

          Disconnected: No supported authentication methods available (server sent: publickey)

          My super user, though, is working fine.

          In my saved session of root in Putty i din’t change anything. The private key is there as i left.

          Thanks for your attention.

          Bobby Iliev
          Site Moderator
          Site Moderator badge
          March 9, 2020

          Hi there,

          In case anyone sees the same error, this might be due to a couple of things:

          • Your SSH key is only added to the /home/your_user/.ssh/authorized_keys and not /root/.ssh/authorized_keys

          • The priviliges of the /root/.ssh/authorized_keys are too open, you need to set the .ssh folder to 700 and the authorized_keys file to 600

          • The SSH root logins are disabled in your SSH config

          Hello

          How i do step four using keys generated by putty?

          This comment has been deleted

            Great tutorial and it works like a charm. Would be better that you can mention the configuration for /etc/hosts and /etc/hostname. This one gives me a headache after I created a sudoer user.

            I can ssh login as root but not as new user, here is what i did:

            adduser newuser
            usermod -aG sudo
            su - newuser
            mkdir ~/.ssh
            chmod 700 ~/.ssh
            nano ~/.ssh/authorizedkeys
            

            Inserted public key (same key as for root)

            chmod 600 ~/.ssh/authorizedkeys
            

            Every step seems to be successful. Why cannot i login as newuser? this happens on both Ubuntu 14 and 16. I am using Putty to generate keys and ssh login.

            Hi jasmineyuan2016,

            The correct file name is authorized_keys and not authorizedkeys (note the underscore character).

            Try again after the creation of the correct file:

            nano ~/.ssh/authorized_keys

            Good luck!

            actually typo, should be authorized_keys. So still doesn’t work. Any other suggestions? or what command i should use to debug ssh error?

            I have done these step over and over and over and I still can’t log in as the user I created. It keeps saying that my password is incorrect when it definitely is not.

            So, I’ve got all of this working, but now I need to get FTP working (so I can upload files to my sparkly, new webserver), BUT, everything I’ve tried, so far, hasn’t worked, and I’m guessing it has to do with the No Password initiative ('cuz the errors always have to do with failed password authentication). How does one do this?!? I even tried using OpenSSL with vsftpd, and the errors were so arcane, whenever I googled them the answers I would hit on were always “Sorry, bud, your server is messed up – contact administration!”

            Hi stlawson,

            You don’t need to use FTP to transfer files. Instead, use a more secure and easy approach: WinSCP.

            Download WinSCP at www.winscp.net.

            Use SCP as a File protocol. To connect, enter your hostname or IP address, username/password.

            Tell me if it helped.

            Hello is there a particular reason, so i get this after following all the guide until step 6?

            ssh: connect to host 192.241.191.42 port 22: Connection refused

            I cant find what i do wrong, please need some help!

            Hi mauriciopayet,

            Connection refused means that the port you are trying to connect to is not actually open. So either you are connecting to the wrong IP address, or to the wrong port, or the server is listening on the wrong port, or is not actually running.

            Please, check:

            -Is yor SSH server running? If not, try: sudo systemctl start sshd -Is your firewall enabled? If so, you must allow ssh on port 22 by running the instructions on step 7 -And, of course, make sure you are connecting using the right IP address for your droplet.

            Best,

            Fernando Pimenta

            Hi thanks for help! I tried the first option and i get wrong password… i am using the password i created previous steps as superuser account… is there anything i should do from here?

            Hello,

            It looks like the port 22 you are trying to SSH through may be closed. This is the default port, so I presume you changed this without changing your firewall settings.

            If you log in to your DigitalOcean account, go to your Droplet and open the ‘console’ you will be able to open port 22 again, or atleast see which port you should be using.

            You could then access your server in Terminal doing something like: ssh -p 22 user@ip-address

            Change the port number {22} and username {user} and IP {ip-address} accordingly.

            I recommend reading the following article (URL below) for guidance, this massively helped me when I was in a similar incident where I was locked out of my own account.

            https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-with-ufw-on-ubuntu-16-04

            Hope this helps

            When i go through Droplet console it asks me for a login, which i should use to access port number info!? really thanks for help!

            Hi @mauriciopayet,

            Just login using the username and the password you set-up for that user. If you didn’t set one up, it’ll be “root” for the username a long with your password.

            Kind regards,

            hi @elliottmangham been working on … i follow all steps in setting up the firewall and allow port 22 but then in mac terminal i try to test log in as step 6 of this guide but it says ssh: connect to host 192.241.191.42 port 22: Connection refused

            Even though i run the command to check port 22 in the console

            why could be this… can i continue setting up the lamp stack?? Please any advice to keep on going is really helpful bro! Thankss thanks thanks

            Hi @mauriciopayet,

            Try logging into ‘Console’ in DigitalOcean in your Droplet, and enter the following:

            sudo ufw allow 22
            

            This will open up the SSH port (22). Then enter the following:

            sudo ufw status numbered
            

            This should list the port settings, and should say port 22 is “ALLOW IN”.

            If so, it should allow you to connect to your server via Terminal. If it continues to refuse access then the issue may be something completely different.

            Perhaps you have disabled password authentication and haven’t yet added your SSH key? Here’s an article that helps you setup SSH keys, though you may have to do in Console if you cannot use SSH in the Terminal: https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys--2

            Hope this helps!

            what if I use this tutorial first?: https://www.digitalocean.com/community/tutorials/how-to-use-ssh-keys-with-putty-on-digitalocean-droplets-windows-users .

            what steps do i need to do in this tutorial if I do that one first? or is there a video tutorial on this guide? i really have no idea what im doing

            I got a trouble with ufw. After setting up, i can’t login to server with my custom login and cert. I disabled ufw and all is ok, but what can i do ? (i work on MacOS Sierra)

            Hello, DO

            I created my new droplet with ssh key and loging in as root was working fine in Putty and Filezilla. I also created a super user and its keys were also all right and working on both terminals. However, this morning when i tried to login as root, the server responded:

            Disconnected: No supported authentication methods available (server sent: publickey)

            My super user, though, is working fine.

            In my saved session of root in Putty i din’t change anything. The private key is there as i left.

            Thanks for your attention.

            Bobby Iliev
            Site Moderator
            Site Moderator badge
            March 9, 2020

            Hi there,

            In case anyone sees the same error, this might be due to a couple of things:

            • Your SSH key is only added to the /home/your_user/.ssh/authorized_keys and not /root/.ssh/authorized_keys

            • The priviliges of the /root/.ssh/authorized_keys are too open, you need to set the .ssh folder to 700 and the authorized_keys file to 600

            • The SSH root logins are disabled in your SSH config

            Hello

            How i do step four using keys generated by putty?

            This comment has been deleted

              Great tutorial and it works like a charm. Would be better that you can mention the configuration for /etc/hosts and /etc/hostname. This one gives me a headache after I created a sudoer user.

              this is wrong:

              usermod -aG sudo sammy
              

              it needs sudo,

              sudo usermod -aG sudo sammy
              

              No, it’s correct. The # hashtag from the shell prompt tells you that this is a root shell Normal user shells are denoted with a $ sign. (Just one character can make a significant difference)

              Since he already switched to the root user, no sudo is necessary. He also mentions it in the paragraph above the command snippet:

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

              As for step 4,

              What I have to do if I no longer have access to my device to which ssh keys belong?

              Regards, Ivan

              This comment has been deleted

                How do you add more than 1 ssh key to a user? Just add onto the next line when nano opening the file? Or is there some sort of format to do this?

                Hi @KelvinZhao,

                Just add one public SSH key per line using nano:

                nano ~/.ssh/authorized_keys

                Cheers,

                Fernando Pimenta

                Followed all the steps,

                Can’t login Permission denied (publickey). On terminal mac.

                It makes no sense that you don’t have automated processes to create users, set firewall, install nginx etc.

                Hi @openanygate,

                Yes, it makes sense. This tutorial is for those that want to learn how to do the things (DIY way).

                But, yes, after that you can automate what you’ve learned.

                Cheers,

                Fernando Pimenta

                First of all: Thanks to the technical writers at Digital Ocean for providing us with these tutorials! They are mostly really helpful and easy to follow!

                @fernandopimenta There are times when I have time and patience and can focus hours on end on stuff, just for the sake of knowing how it works. This applies to a lot of things, mechanics, physics, electronics, IT … sadly, these days, those moments are seldom.

                Most of the time I prefer a solution that works. I don’t necessarily need to know, how the little cogs and wheels work inside of it. If you tell me, in order to use something you inevitable need to know every detail of it, I ask you: Did you ever press a switch on a device, without exactly knowing the inner workings of it?

                It is nice to learn how to setup stuff like this. It provides benefit. But if I need a quick little Ubuntu server to test something out, that needs to be let alone in the wild for some time, I don’t have the f***ing time to read 20 pages of documentary of which half is already outdated and replaced by other pages, tutorials and best practices.

                Just give me a ready-to-deploy package I can work with and leave it to me if I care to learn how it actually works.

                All the best, Noël Ströhmer-Lohfink

                Hi Noël,

                So, in this case, you can click on “One-click apps” intead of “Distributions” during droplet creation, so that you can choose one of the various pre-installed systems: LAMP on 16.04, LEMP on 16.04, Wordpress on 16.04, Django on 16.04 and so on.

                Best,

                Fernando Pimenta

                I want to know from the experts as to what exactly are the usage of setting up the server on ubuntu os and further as to how it will be beneficial to host my third-party website? Kindly post your guidelines quickly. Thanks

                Is the basic firewall setup still recommended given that DO allows you to configure firewalls very easily in the dashboard now?

                im stuck on step 4 and 5 im using ubuntu 17.4 i believe and when i type nano ~/.ssh/authorized_keys it shows a empty box with comand keys at the bottom of the page it will not let me paste my ssh-rsa HELP!

                I have installed One Click Wordpress App. Now when I do :

                ssh root@your_server_ip
                
                

                I get following error. Can someone help, I cannot do later steps because of this error. I am guessing because of this i cannot install Nginx.

                Permission denied (publickey).
                
                

                Great article thanks. couldn’t find: PubkeyAuthentication yes ChallengeResponseAuthentication no in ssh_config. do we need to add them if not found?

                These Digital Ocean tuts are great for beginners. Thanks a lot.

                If you’re working with other devs/sys admins I would create an ssh group and set the permissions like so: sudo chmod 640 ~/.ssh/authorized_keys

                6 -> Owner has read and write access 4 -> Group has read access 0 -> Other does not have any permissions

                Permissions: 1 – can execute 2 – can write 4 – can read

                Then you can go into the sshd_config file and make the edits specified by D.O.

                source: http://www.thinkplexx.com/learn/article/unix/command/chmod-permissions-flags-explained-600-0600-700-777-100-etc

                This comment has been deleted

                  I’m new to Linux and have a VPS with Ubuntu 16.04. I want to follow this guide, but I am already stuck when talking about local user.

                  Does this only apply if you are able to locally log into the machine?

                  I don’t want to lock myself out as the only way I can connect (that I know of) is through SSH.

                  Hello DO community I have one question. I have done the following: Generated key pairs Installed public key in server Disabled ssh password authentication.

                  I am able to login using keys only. I dont have any problem at all. My concern is that its seems to be using id_rsa.pub instad of id_rsa to login. I have tested removing each of the files at a time from my /home/username/.ssh/ folder. I login successfully when my id_rsa.pub is in the folder only. But cannot connect when my id_rsa is in the folder only.

                  I will appreciate an answer, thanks!

                  Hi @imzamont,

                  The id_rsa.pub is a public key you use to connect to another host without a password, if that host has your public key listed in its authorized_keys file.

                  Identity keys, id_rsa, are usually stored in a user’s .ssh directory, for example, /home/<user>/.ssh.

                  If you need to change the location, you have o inform this in OpenSSH options (but it is generally not necessary).

                  Best regards,

                  Fernando Pimenta

                  Hello fernandopimenta, thanks for your reply. The thing is that I want to have access to my server from another computer using the SAME key. So I just have to put the id_rsa.pub file in the others computer /home/<user>/.ssh folder

                  I thought the private key was the one needed to have access to the server. Correct me if I am wrong

                  Hi @imzamont,

                  In order to avoid confusion regarding the point from which you are connecting, I’ll indicate you two good tutorials from DigitalOcean:

                  https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys--2

                  https://www.digitalocean.com/community/tutorials/how-to-configure-ssh-key-based-authentication-on-a-linux-server

                  I hope that these documents help you with your questions.

                  Let me know if you need more help.

                  Best regards,

                  Fernando Pimenta

                  Hello @fernandopimenta Thanks for your time. Well it seems that I have configured somethig wrong, I will keep testing to make sure I understand correctly.

                  Hi, just a share for others:

                  I was having issues with SSH setup, and it turns out the ssh-agent was NOT RUNNING by default on my droplet so i have to turn it on:

                  ```eval `ssh-agent -s````

                  then check for keys: ssh-add -l

                  found out there were not keys, then i went through the steps in this tutorial to get ssh setup. This took me over a day to figure out, PLEASE add this to your tutorial so people know to check to see if ssh is on, as it seems like it is all working, but then when you try to ssh user@ip it fails.

                  Hi All,

                  instead of taking the risk of locking ourselves out I’d suggest a client side enforced pubkey auth test like the following one.

                  ssh user@host -o PubkeyAuthentication=true

                  If this works you can safely disable simple password based logins :)

                  Regards, L

                  Hello, it’s a great article, but I have a question about the second option in the paragraph about copying of the key. If I select an SSH key during a DigitalOcean Droplet creation could I simply sudo cp /root/.ssh/authorized_keys ~/.ssh/ and change the owner of the copied file instead of creating new file and copying my public key into it using nano and clipboard?

                  If I followed https://www.digitalocean.com/community/tutorials/how-to-use-ssh-keys-with-digitalocean-droplets and now have a ‘root’ user that uses SSH, do I need to create another user with an SSH key as described in this page?

                  What do you mean by “need”? Technically you could use the root user via ssh and do all the things.

                  From a best-practice and security perspective you should create a user with sudo-privilege and add your ssh key for that user as well and then deactivate login-as-root altogether.

                  Because once your day-to-day user account gets hacked, the intruder hasn’t gained that much. But if he can become root user, you’re basically fucked. So securing root user and do the work with a user with less power is preferred.

                  Although this whole scenario has become a lot less daunting with the advent of cloud computing. Apart from sensible data theft, the recovery of such an attack is as easy as deleting the compromised droplet and create it again from snapshot/backup. So depending on what you plan to do on your droplet, one could argue that root access might just be fine.

                  Ne however prepared for professionals yelling at you for doing it. ;)

                  I use the Ghost 1-click app to create the droplet and after setting up the installation of Ghost, I follow this tutorial Step Five. But when I try to login using the newly created username using putty, the program displays fatal error:

                  Disconnected: No supported authentication methods available (server sent: publickey)

                  I have many times check if I’m missing any steps but I’ve tried many times. Anyone got the same problem or have the solution?

                  Before you “Enable” the FireWall, you really should look at what you’ve added to the rules. sudo ufw show added

                  If you try to show status it will just tell you it’s not enabled.

                  alt text
                  Thumbs Up

                  OK so I have this in my ssh_config:

                  # Site-wide defaults for some commonly used options.  For a comprehensive
                  # list of available options, their meanings and defaults, please see the
                  # ssh_config(5) man page.
                  
                  Host *
                  PasswordAuthentication no
                  PubkeyAuthentication yes
                  ChallengeResponseAuthentication no
                  [edited out commented out lines]
                      SendEnv LANG LC_*
                      HashKnownHosts yes
                      GSSAPIAuthentication yes
                      GSSAPIDelegateCredentials no
                  
                  

                  …and it’s still asking me for my password, after restarting sshd. What gives?

                  This comment has been deleted

                    The new version of Ubuntu is installed the same way? I could not install.

                    Hi @davidanavarro84,

                    You can check the steps for Ubuntu 18.04 in the new version of this tutorial:

                    https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-18-04

                    Best regards,

                    Fernando Pimenta

                    This seemed to work well up until Step 6 when I was testing the log-in.

                    When I enter “ssh name@IPAddress”, it says “ssh: connect to host IPAddress port 22: Connection timed out”

                    What can I do to troubleshoot this?

                    If you want to use the same ssh key setup as root for the user it should be possible to copy it.

                    cp -R ~/.ssh/ /home/sammy/.shh && chown sammy:sammy /home/sammy/.shh/
                    
                    Bobby Iliev
                    Site Moderator
                    Site Moderator badge
                    October 19, 2020

                    Hello,

                    For anyone interested,I just created a similar video demo on how to do the initial server setup as described in this tutorial:

                    Hope that this helps!

                    Regards, Bobby

                    Try DigitalOcean for free

                    Click below to sign up and get $200 of credit to try our products over 60 days!

                    Sign up

                    Join the Tech Talk
                    Success! Thank you! Please check your email for further details.

                    Please complete your information!

                    Become a contributor for community

                    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                    DigitalOcean Documentation

                    Full documentation for every DigitalOcean product.

                    Resources for startups and SMBs

                    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                    Get our newsletter

                    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                    New accounts only. By submitting your email you agree to our Privacy Policy

                    The developer cloud

                    Scale up as you grow — whether you're running one virtual machine or ten thousand.

                    Get started for free

                    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                    *This promotional offer applies to new accounts only.