One place for hosting & domains

      How To Deploy a Go Web Application Using Nginx on Ubuntu 18.04


      The author selected the Tech Education Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Go is a general-purpose programming language that is gradually becoming one of the most popular web back-end programming languages. By focusing on simplicity, the designers of Go created a language that is both easy to learn and faster than many other languages for web applications, leveraging efficient features like its ability to handle multiple requests at a time due to its concurrency. Because of this, deploying a web application in Go will be useful to many back-end developers.

      Nginx is one of the most popular web servers in the world due to its lightweight resource usage and its reliability under load. Many of the largest and most highly trafficked sites on the internet depend on Nginx to serve their content. In deployment, Nginx is often used as a load balancer or a reverse proxy to increase security and make the application more robust. In conjunction with a Go web back-end, Nginx can serve up a powerful and fast web application.

      In this tutorial, you will build a Hello World web application in Go and deploy it on an Ubuntu 18.04 server using Nginx as a reverse proxy.

      Prerequisites

      To follow this tutorial, you will need the following:

      Additionally, in order to achieve a production-grade deployment of your Go web application, it’s important that you keep your server secure by installing a TLS/SSL certificate. This step is strongly encouraged. To secure your Go web application, follow How To Secure Nginx with Let’s Encrypt on Ubuntu 18.04 after Step 3 of this tutorial to obtain the free TLS/SSL certificate.

      Step 1 — Building the Go Web Application

      In this step, you will build a sample Go web application that displays Hello World at your_domain and greets the user at your_domain/greet/. If you would like to learn more about the basics of programming in Go, check out our How To Write Your First Program in Go article.

      First, create a new directory in your GOPATH directory to hold the source file. You can name the folder whatever you like, but this tutorial will use go-web:

      Following the file structure suggested in the prerequisite tutorial How To Install Go and Set Up a Local Programming Environment on Ubuntu 18.04, this will give your directory the path of ~/go/go-web.

      Next, run the following to change directory to your newly created folder in your GOPATH:

      Use nano or your preferred text editor to create a file named main.go, which will contain the source code for your web application:

      To create the functionality of the Hello World application, add the following Go code into the newly created main.go file:

      ~/go/go-web/main.go

      package main
      
      import (
          "fmt"
          "net/http"
      )
      
      func main() {
          http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
              fmt.Fprintf(w, "Hello World")
          })
      
          http.HandleFunc("/greet/", func(w http.ResponseWriter, r *http.Request) {
              name := r.URL.Path[len("/greet/"):]
              fmt.Fprintf(w, "Hello %sn", name)
          })
      
          http.ListenAndServe(":9990", nil)
      }
      

      Now let's go through what the preceding code snippet will do, starting from the first line.

      First, you wrote the entry point into your application:

      ~/go/go-web/main.go

      package main
      ...
      

      The package main tells the Go compiler to compile this file as an executable program instead of as a shared library.

      Next, you have the import statements:

      ~/go/go-web/main.go

      ...
      
      import (
          "fmt"
          "net/http"
      )
      ...
      

      This snippet imports the necessary modules required for this code to work, which include the standard fmt package and the net/http package for your web server.

      The next snippet creates your first route in the main function, which is the entry point of any Go application:

      ~/go/go-web/main.go

      ...
      func main () {
          http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
              fmt.Fprintf(w, "Hello World")
          })
        ...
      }
      ...
      

      A parent route / is created within func main, which will return the text Hello World when requested.

      The second route as shown in the following snippet accepts a URL parameter, in this case a name, to display accompanied by a greeting.

      ~/go/go-web/main.go

      ...
      func main () {
        ...
          http.HandleFunc("/greet/", func(w http.ResponseWriter, r *http.Request) {
              name := r.URL.Path[len("/greet/"):]
              fmt.Fprintf(w, "Hello %sn", name)
          })
      ...
      }
      ...
      

      This uses Go's URL.Path to store the value right after /greet/ and pass it down as the name from the URL parameter.

      Finally, you instantiate your server:

      ~/go/go-web/main.go

      ...
      func main () {
        ...
        http.ListenAndServe(":9990", nil)
      }
      

      The preceding snippet starts the server and exposes your application via port 9990 using Go's inbuilt http server.

      Once you are finished examining the code in main.go, save the file and quit your text editor.

      Next, build the binary executable of your application by running:

      The preceding command will compile main.go to produce an executable titled main.

      You have created your sample Go web application. Next, you will create a systemd unit file to keep your application running in the background even when you are not accessing your server.

      Step 2 — Creating a Systemd Unit File

      In this step, you will create a systemd unit file to keep your application running in the background even when a user logs out of the server. This will make your application persistent, bringing you one step closer to a production-grade deployment.

      First, create a new file in /lib/systemd/system directory named goweb.service using nano or you preferred text editor:

      • sudo nano /lib/systemd/system/goweb.service

      To set the parameters of the service, add the following snippet into the file.

      /lib/systemd/system/goweb.service

      [Unit]
      Description=goweb
      
      [Service]
      Type=simple
      Restart=always
      RestartSec=5s
      ExecStart=/home/user/go/go-web/main
      
      [Install]
      WantedBy=multi-user.target
      

      The ExecStart=/home/user/go/go-web/main variable specifies that the point of entry for this service is through the main executable located in the /home/user/go/go-web directory, where user is the server non-root sudo account username. Restart=always ensures that systemd will always try to restart the program if it stops. On the next line, RestartSec=5s sets a five-second wait time between restart attempts. WantedBy=multi-user.target specifies in what state your server will enable the service.

      Save and exit the file.

      Now that you've written the service unit file, start your Go web service by running:

      To confirm if the service is running, use the following command:

      • sudo service goweb status

      You'll receive the following output:

      Output

      ● goweb.service - goweb Loaded: loaded (/lib/systemd/system/goweb.service; disabled; vendor preset: enabled) Active: active (running) since Wed 2019-07-17 23:28:57 UTC; 6s ago Main PID: 1891 (main) Tasks: 4 (limit: 1152) CGroup: /system.slice/goweb.service └─1891 /home/user/go/go-web/main

      To learn more about working with systemd unit file, take a look at Understanding Systemd Units and Unit Files.

      Now that you have your application up and running, you can set up the Nginx reverse proxy.

      Step 3 — Setting Up a Reverse Proxy with Nginx

      In this step, you will create an Nginx server block and set up an Nginx reverse proxy to expose your application to the internet.

      First, change your working directory to the Nginx sites-available directory:

      • cd /etc/nginx/sites-available

      Create a new file with the name of the domain on which you wish to expose your application. This tutorial will use your_domain:

      Add the following lines into the file to establish the settings for your_domain:

      /etc/nginx/sites-available/your_domain

      server {
          server_name your_domain www.your_domain;
      
          location / {
              proxy_pass http://localhost:9990;
          }
      }
      

      This Nginx server block uses proxy_pass to serve the Go web application on your server's IP address indicated as localhost to make it run on port 9990. server_name indicates the domain name mapped to your IP address, in this case your_domain and www.your_domain.

      Next, create a symlink of this Nginx configuration in the sites-enabled folder by running the following command:

      • sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/your_domain

      A symlink is a shortcut of a file in another location. The newly created shortcut will always reference the original file to adjust to updates when edits are made to it. Nginx requires a copy of the configuration in both directories.

      Next, reload your Nginx configurations by running the reload command:

      To make sure that your deployment is working, visit http://your_domain in your browser. You will be greeted with a Hello World text string.

      Note: As mentioned in the Prerequisites section, at this point it is recommended to enable SSL/TLS on your server. This will make sure that all communication between the application and its visitors will be encrypted, which is especially important if the application asks for sensitive information such as a login or password. Follow How To Secure Nginx with Let's Encrypt on Ubuntu 18.04 now to obtain a free SSL certificate for Nginx on Ubuntu 18.04. After obtaining your SSL/TLS certificates, come back and complete this tutorial.

      You have now set up the Nginx reverse proxy to expose your application at your domain name, and secured your Go web application with SSL/TLS. In the next step, you will be testing your application over a secure connection.

      Step 4 — Testing the Application

      In this step, you will test your application over a secure connection to make sure everything is working.

      Open your preferred web browser, visit https://your_domain:

      Hello World Page Display

      You will receive a simple Hello World message. Receiving this message when using https:// in the URL indicates that your application is being served over a secure connection.

      Next, try visiting the second route https://your_domain/greet/your-name, replacing your-name with whichever name you want your app to greet:

      Greeting Page Display

      The application will return a simple greeting along with your-name, which is based on the parameter passed to the URL.

      Once you have received these results, you have successfully deployed your Go web application.

      Conclusion

      In this tutorial, you created a simple web application with Go using its standard libraries, set up a reverse proxy using Nginx, and used a SSL certificate on your domain to secure your app. To learn more about Go, check their official documentation. Also, you can look at our series How To Code in Go to learn more about programming in this efficient language.



      Source link

      How To Install phpMyAdmin From Source on Debian 10


      Introduction

      While many users need the functionality of a database management system like MariaDB, they may not feel comfortable interacting with the system solely from the MariaDB prompt.

      phpMyAdmin was created so that users can interact with MariaDB through a web interface. In this guide, we’ll discuss how to install and secure phpMyAdmin so that you can safely use it to manage your databases on a Debian 10 system.

      Prerequisites

      Before you get started with this guide, you’ll need the following:

      Note: MariaDB is a community-developed fork of MySQL, and although the two programs are closely related, they are not completely interchangeable. While phpMyAdmin was designed specifically for managing MySQL databases and makes reference to MySQL in various dialogue boxes, rest assured that your installation of MariaDB will work correctly with phpMyAdmin.

      Finally, there are important security considerations when using software like phpMyAdmin, since it:

      • Communicates directly with your MariaDB installation
      • Handles authentication using MariaDB credentials
      • Executes and returns results for arbitrary SQL queries

      For these reasons, and because it is a widely-deployed PHP application which is frequently targeted for attack, you should never run phpMyAdmin on remote systems over a plain HTTP connection.

      If you do not have an existing domain configured with an SSL/TLS certificate, you can follow this guide on securing Apache with Let’s Encrypt on Debian 10 to set one up. This will require you to register a domain name, create DNS records for your server, and set up an Apache Virtual Host.

      Once you are finished with these steps, you’re ready to get started with this guide.

      Before installing and configuring phpMyAdmin, the official documentation recommends that you install a few PHP extensions onto your server to enable certain functionalities and improve performance.

      If you followed the prerequisite LAMP stack tutorial, several of these modules will have been installed along with the php package. However, it’s recommended that you also install these packages:

      • php-mbstring: a PHP extension used to manage non-ASCII strings and convert strings to different encodings
      • php-zip: a PHP module that supports uploading .zip files to phpMyAdmin
      • php-gd: another PHP module, this one enables support for the GD Graphics Library

      First, update your server’s package index if you’ve not done so recently:

      Then use apt to pull down the files and install them on your system:

      • sudo apt install php-mbstring php-zip php-gd

      Next, we can install phpMyAdmin. As of this writing, phpMyAdmin is not available from the default Debian repositories, so you will need to download the source code to your server from the phpMyAdmin site.

      In order to do that, navigate to the phpMyAdmin Downloads page, scroll down to the table with download links for the latest stable release, and copy the download link ending in tar.gz. This link points to an archive file known as a tarball that, when extracted, will create a number of files on your system. At the time of this writing, the latest release is version 4.9.0.1.

      Note: On this Downloads page, you will notice that there are download links labeled all-languages and english. The all-languages links will download a version of phpMyAdmin that will allow you to select one of 72 available languages, while the english links will only allow you to use phpMyAdmin in English.

      This guide will use the all-languages package to illustrate how to install phpMyAdmin, but if you plan to use phpMyAdmin in English, you can install the english package. Just be sure to replace the links and file names as necessary in the following commands.

      Replace the link in the following wget command with the download link you just copied, then press ENTER. This will run the command and download the tarball to your server:

      • wget https://files.phpmyadmin.net/phpMyAdmin/4.9.0.1/phpMyAdmin-4.9.0.1-all-languages.tar.gz

      Then extract the tarball:

      • tar xvf phpMyAdmin-4.9.0.1-all-languages.tar.gz

      This will create a number of new files and directories on your server under a parent directory named phpMyAdmin-4.9.0.1-all-languages.

      Then run the following command. This will move the phpMyAdmin-4.9.0.1-all-languages directory and all its subdirectories to the /usr/share/ directory, the location where phpMyAdmin expects to find its configuration files by default. It will also rename the directory in place to just phpmyadmin:

      • sudo mv phpMyAdmin-4.9.0.1-all-languages/ /usr/share/phpmyadmin

      With that, you've installed phpMyAdmin, but there are a number of configuration changes you must make in order to be able to access phpMyAdmin through a web browser.

      Step 2 — Configuring phpMyAdmin Manually

      When installing phpMyAdmin with a package manager, as one might in an Ubuntu environment, phpMyAdmin defaults to a "Zero Configuration" mode which performs several actions automatically to set up the program. Because we installed it from source in this guide, we will need to perform those steps manually.

      To begin, make a new directory where phpMyAdmin will store its temporary files:

      • sudo mkdir -p /var/lib/phpmyadmin/tmp

      Set www-data — the Linux user profile that web servers like Apache use by default for normal operations in Ubuntu and Debian systems — as the owner of this directory:

      • sudo chown -R www-data:www-data /var/lib/phpmyadmin

      The files you extracted previously include a sample configuration file that you can use as your base configuration file. Make a copy of this file, keeping it in the /usr/share/phpmyadmin directory, and rename it config.inc.php:

      • sudo cp /usr/share/phpmyadmin/config.sample.inc.php /usr/share/phpmyadmin/config.inc.php

      Open this file using your preferred text editor. Here, we'll use nano:

      • sudo nano /usr/share/phpmyadmin/config.inc.php

      phpMyAdmin uses the cookie authentication method by default, which allows you to log in to phpMyAdmin as any valid MariaDB user with the help of cookies. In this method, the MariaDB user password is stored and encrypted with the Advanced Encryption Standard (AES) algorithm in a temporary cookie.

      Historically, phpMyAdmin instead used the Blowfish cipher for this purpose, and this is still reflected in its configuration file. Scroll down to the line that begins with $cfg['blowfish_secret']. It will look like this:

      /usr/share/phpmyadmin/config.inc.php

      . . .
      $cfg['blowfish_secret'] = ''; /* YOU MUST FILL IN THIS FOR COOKIE AUTH! */
      . . .
      

      In between the single quotes, enter a string of 32 random characters. This isn't a passphrase you need to remember, it will just be used internally by the AES algorithm:

      /usr/share/phpmyadmin/config.inc.php

      . . .
      $cfg['blowfish_secret'] = 'STRINGOFTHIRTYTWORANDOMCHARACTERS'; /* YOU MUST FILL IN THIS FOR COOKIE AUTH! */
      . . .
      

      Note: If the passphrase you enter here is shorter than 32 characters in length, it will result in the encrypted cookies being less secure. Entering a string longer than 32 characters, though, won't cause any harm.

      To generate a truly random string of characters, you can install and use the pwgen program:

      By default, pwgen creates easily pronounceable, though less secure, passwords. However, by including the -s flag, as in the following command, you can create a completely random, difficult-to-memorize password. Note the final two arguments to this command: 32, which dictates how long the password string pwgen will generate should be; and 1 which tells pwgen how many strings it should generate:

      Next, scroll down to the comment reading /* User used to manipulate with storage */. This section includes some directives that define a MariaDB database user named pma which performs certain administrative tasks within phpMyAdmin. According to the official documentation, this special user account isn't necessary in cases where only one user will access phpMyAdmin, but it is recommended in multi-user scenarios.

      Uncomment the controluser and controlpass directives by removing the preceding slashes. Then update the controlpass directive to point to a secure password of your choosing. If you don't do this, the default password will remain in place and unknown users could easily gain access to your database through the phpMyAdmin interface.

      After making these changes, this section of the file will look like this:

      /usr/share/phpmyadmin/config.inc.php

      . . .
      /* User used to manipulate with storage */
      // $cfg['Servers'][$i]['controlhost'] = '';
      // $cfg['Servers'][$i]['controlport'] = '';
      $cfg['Servers'][$i]['controluser'] = 'pma';
      $cfg['Servers'][$i]['controlpass'] = 'password';
      . . .
      

      Below this section, you'll find another section preceded by a comment reading /* Storage database and tables */. This section includes a number of directives that define the phpMyAdmin configuration storage, a database and several tables used by the administrative pma database user. These tables enable a number of features in phpMyAdmin, including Bookmarks, comments, PDF generation, and more.

      Uncomment each line in this section by removing the slashes at the beginning of each line so it looks like this:

      /usr/share/phpmyadmin/config.inc.php

      . . .
      /* Storage database and tables */
      $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
      $cfg['Servers'][$i]['bookmarktable'] = 'pma__bookmark';
      $cfg['Servers'][$i]['relation'] = 'pma__relation';
      $cfg['Servers'][$i]['table_info'] = 'pma__table_info';
      $cfg['Servers'][$i]['table_coords'] = 'pma__table_coords';
      $cfg['Servers'][$i]['pdf_pages'] = 'pma__pdf_pages';
      $cfg['Servers'][$i]['column_info'] = 'pma__column_info';
      $cfg['Servers'][$i]['history'] = 'pma__history';
      $cfg['Servers'][$i]['table_uiprefs'] = 'pma__table_uiprefs';
      $cfg['Servers'][$i]['tracking'] = 'pma__tracking';
      $cfg['Servers'][$i]['userconfig'] = 'pma__userconfig';
      $cfg['Servers'][$i]['recent'] = 'pma__recent';
      $cfg['Servers'][$i]['favorite'] = 'pma__favorite';
      $cfg['Servers'][$i]['users'] = 'pma__users';
      $cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
      $cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
      $cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
      $cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
      $cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
      $cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
      . . .
      

      These tables don't yet exist, but we will create them shortly.

      Lastly, scroll down to the bottom of the file and add the following line. This will configure phpMyAdmin to use the /var/lib/phpmyadmin/tmp directory you created earlier as its temporary directory. phpMyAdmin will use this temporary directory as a templates cache which allows for faster page loading:

      /usr/share/phpmyadmin/config.inc.php

      . . .
      $cfg['TempDir'] = '/var/lib/phpmyadmin/tmp';
      

      Save and close the file after adding this line. If you used nano, you can do so by pressing CTRL + X, Y, then ENTER.

      Next, you'll need to create the phpMyAdmin storage database and tables. When you installed phpMyAdmin in the previous step, it came with a file named create_tables.sql. This SQL file contains all the commands needed to create the configuration storage database and tables phpMyAdmin needs to function correctly.

      Run the following command to use the create_tables.sql file to create the configuration storage database and tables:

      • sudo mariadb < /usr/share/phpmyadmin/sql/create_tables.sql

      Following that, you'll need to create the administrative pma user. Open up the MariaDB prompt:

      From the prompt, run the following command to create the pma user and grant it the appropriate permissions. Be sure to change password to align with the password you defined in the config.inc.php file:

      • GRANT SELECT, INSERT, UPDATE, DELETE ON phpmyadmin.* TO 'pma'@'localhost' IDENTIFIED BY 'password';

      If haven't created one already, you should also create a regular MariaDB user for the purpose of managing databases through phpMyAdmin, as it’s recommended that you log in using another account than the pma user. You could create a user that has privileges to all tables within the database, as well as the power to add, change, and remove user privileges, with this command. Whatever privileges you assign to this user, be sure to give it a strong password as well:

      • GRANT ALL PRIVILEGES ON *.* TO 'sammy'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;

      Following that, exit the MariaDB shell:

      phpMyAdmin is now fully installed and configured on your server. However, your Apache server does not yet know how to serve the application. To resolve this, we will create an Apache configuration file for it.

      Step 3 — Configuring Apache to Serve phpMyAdmin

      When installing phpMyAdmin from the default repositories, the installation process creates an Apache configuration file automatically and places it in the /etc/apache2/conf-enabled/ directory. Because we installed phpMyAdmin from source, however, we will need to create and enable this file manually.

      Create a file named phpmyadmin.conf in the /etc/apache2/conf-available/ directory:

      • sudo nano /etc/apache2/conf-available/phpmyadmin.conf

      Then add the following content to the file

      /etc/apache2/conf-available/phpmyadmin.conf

      # phpMyAdmin default Apache configuration
      
      Alias /phpmyadmin /usr/share/phpmyadmin
      
      <Directory /usr/share/phpmyadmin>
          Options SymLinksIfOwnerMatch
          DirectoryIndex index.php
      
          <IfModule mod_php5.c>
              <IfModule mod_mime.c>
                  AddType application/x-httpd-php .php
              </IfModule>
              <FilesMatch ".+.php$">
                  SetHandler application/x-httpd-php
              </FilesMatch>
      
              php_value include_path .
              php_admin_value upload_tmp_dir /var/lib/phpmyadmin/tmp
              php_admin_value open_basedir /usr/share/phpmyadmin/:/etc/phpmyadmin/:/var/lib/phpmyadmin/:/usr/share/php/php-gettext/:/usr/share/php/php-php-gettext/:/usr/share/javascript/:/usr/share/php/tcpdf/:/usr/share/doc/phpmyadmin/:/usr/share/php/phpseclib/
              php_admin_value mbstring.func_overload 0
          </IfModule>
          <IfModule mod_php.c>
              <IfModule mod_mime.c>
                  AddType application/x-httpd-php .php
              </IfModule>
              <FilesMatch ".+.php$">
                  SetHandler application/x-httpd-php
              </FilesMatch>
      
              php_value include_path .
              php_admin_value upload_tmp_dir /var/lib/phpmyadmin/tmp
              php_admin_value open_basedir /usr/share/phpmyadmin/:/etc/phpmyadmin/:/var/lib/phpmyadmin/:/usr/share/php/php-gettext/:/usr/share/php/php-php-gettext/:/usr/share/javascript/:/usr/share/php/tcpdf/:/usr/share/doc/phpmyadmin/:/usr/share/php/phpseclib/
              php_admin_value mbstring.func_overload 0
          </IfModule>
      
      </Directory>
      
      # Authorize for setup
      <Directory /usr/share/phpmyadmin/setup>
          <IfModule mod_authz_core.c>
              <IfModule mod_authn_file.c>
                  AuthType Basic
                  AuthName "phpMyAdmin Setup"
                  AuthUserFile /etc/phpmyadmin/htpasswd.setup
              </IfModule>
              Require valid-user
          </IfModule>
      </Directory>
      
      # Disallow web access to directories that don't need it
      <Directory /usr/share/phpmyadmin/templates>
          Require all denied
      </Directory>
      <Directory /usr/share/phpmyadmin/libraries>
          Require all denied
      </Directory>
      <Directory /usr/share/phpmyadmin/setup/lib>
          Require all denied
      </Directory>
      

      This is the default phpMyAdmin Apache configuration file found on Ubuntu installations, though it will be adequate for a Debian setup as well.

      Save and close the file, then enable it by typing:

      • sudo a2enconf phpmyadmin.conf

      Then reload the apache2 service to put the configuration changes into effect:

      • sudo systemctl reload apache2

      Following that, you'll be able to access the phpMyAdmin login screen by navigating to the following URL in your web browser:

      https://your_domain/phpmyadmin
      

      You'll see the following login screen:

      phpMyAdmin login screen

      Log in to the interface with the MariaDB username and password you configured. After logging in, you'll see the user interface, which will look something like this:

      phpMyAdmin user interface

      Now that you’re able to connect and interact with phpMyAdmin, all that’s left to do is harden your system’s security to protect it from attackers.

      Step 4 — Securing Your phpMyAdmin Instance

      Because of its ubiquity, phpMyAdmin is a popular target for attackers, and you should take extra care to prevent unauthorized access. One of the easiest ways of doing this is to place a gateway in front of the entire application by using Apache's built-in .htaccess authentication and authorization functionalities.

      To do this, you must first enable the use of .htaccess file overrides by editing your Apache configuration file.

      Edit the linked file that has been placed in your Apache configuration directory:

      • sudo nano /etc/apache2/conf-available/phpmyadmin.conf

      Add an AllowOverride All directive within the <Directory /usr/share/phpmyadmin> section of the configuration file, like this:

      /etc/apache2/conf-available/phpmyadmin.conf

      <Directory /usr/share/phpmyadmin>
          Options FollowSymLinks
          DirectoryIndex index.php
          AllowOverride All
      
          <IfModule mod_php5.c>
          . . .
      

      When you have added this line, save and close the file.

      To implement the changes you made, restart Apache:

      • sudo systemctl restart apache2

      Now that you have enabled .htaccess use for your application, you need to create one to actually implement some security.

      In order for this to be successful, the file must be created within the application directory. You can create the necessary file and open it in your text editor with root privileges by typing:

      • sudo nano /usr/share/phpmyadmin/.htaccess

      Within this file, enter the following content:

      /usr/share/phpmyadmin/.htaccess

      AuthType Basic
      AuthName "Restricted Files"
      AuthUserFile /usr/share/phpmyadmin/.htpasswd
      Require valid-user
      

      Here is what each of these lines mean:

      • AuthType Basic: This line specifies the authentication type that you are implementing. This type will implement password authentication using a password file.
      • AuthName: This sets the message for the authentication dialog box. You should keep this generic so that unauthorized users won't gain any information about what is being protected.
      • AuthUserFile: This sets the location of the password file that will be used for authentication. This should be outside of the directories that are being served. We will create this file shortly.
      • Require valid-user: This specifies that only authenticated users should be given access to this resource. This is what actually stops unauthorized users from entering.

      When you are finished, save and close the file.

      The location that you selected for your password file was /usr/share/phpmyadmin/.htpasswd. You can now create this file and pass it an initial user with the htpasswd utility:

      • sudo htpasswd -c /usr/share/phpmyadmin/.htpasswd username

      You will be prompted to select and confirm a password for the user you are creating. Afterwards, the file is created with the hashed password that you entered.

      If you want to enter an additional user, you need to do so without the -c flag, like this:

      • sudo htpasswd /etc/phpmyadmin/.htpasswd additionaluser

      Now, when you access your phpMyAdmin subdirectory, you will be prompted for the additional account name and password that you just configured:

      https://your_domain_or_IP/phpmyadmin
      

      phpMyAdmin apache password

      After entering the Apache authentication, you'll be taken to the regular phpMyAdmin authentication page to enter your MariaDB credentials. This setup adds an additional layer of security, which is desirable since phpMyAdmin has suffered from vulnerabilities in the past.

      Conclusion

      You should now have phpMyAdmin configured and ready to use on your Debian 10 server. Using this interface, you can easily create databases, users, tables, etc., and perform the usual operations like deleting and modifying structures and data.



      Source link

      How To Deploy an ASP.NET Core Application with MySQL Server Using Nginx on Ubuntu 18.04


      The author selected the Open Source Initiative to receive a donation as part of the Write for DOnations program.

      Introduction

      ASP.NET Core is a high-performant, open-source framework for building modern web applications, meant to be a more modular version of Microsoft’s ASP.NET Framework. Released in 2016, it can run on several operating systems such as Linux and macOS. This enables developers to target a particular operating system for development based on design requirements. With ASP.NET Core, a developer can build any kind of web application or service irrespective of the complexity and size. Developers can also make use of Razor pages to create page-focused design working on top of the traditional Model-View-Controller (MVC) pattern.

      ASP.NET Core provides the flexibility to integrate with any front-end frameworks to handle client-side logic or consume a web service. You could, for example, build a RESTful API with ASP.NET Core and easily consume it with JavaScript frameworks such as Angular, React, and Vue.js.

      In this tutorial you’ll set up and deploy a production-ready ASP.NET Core application with a MySQL Server on Ubuntu 18.04 using Nginx. You will deploy a demo ASP.NET Core application similar to the application from Microsoft’s documentation and hosted on GitHub. Once deployed, the demo application will allow you to create a list of movies and store it in the database. You’ll be able to create, read, update, and delete records from the database. You can use this tutorial to deploy your own ASP.NET Core application instead; it’s possible you’ll have to implement extra steps that include generating a new migration file for your database.

      Prerequisites

      You will need the following for this tutorial:

      Step 1 — Installing .NET Core Runtime

      A .NET Core runtime is required to successfully run a .NET Core application, so you’ll start by installing this to your machine. First, you need to register the Microsoft Key and product repository. After that, you will install the required dependencies.

      First, logged in as your new created user, make sure you’re in your root directory:

      Next, run the following command to register the Microsoft key and product repository:

      • wget -q https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb

      Use dpkg with the -i flag to install the specified file:

      • sudo dpkg -i packages-microsoft-prod.deb

      To facilitate the installation of other packages required for your application, you will install the universe repository with the following command:

      • sudo add-apt-repository universe

      Next install the apt-transport package to allow the use of repositories accessed via the HTTP Secure protocol:

      • sudo apt install apt-transport-https

      Now, run the following command to download the packages list from the repositories and update them to get information on the newest versions of packages and their dependencies:

      Finally, you can install the .NET runtime SDK with:

      • sudo apt install dotnet-sdk-2.2

      You will be prompted with the details of the size of additional files that will be installed. Type Y and hit ENTER to continue.

      Now that you're done installing the .NET Core runtime SDK on the server, you are almost ready to download the demo application from GitHub and set up the deployment configuration. But first, you'll create the database for the application.

      Step 2 — Creating a MySQL User and Database

      In this section, you will create a MySQL server user, create a database for the application, and grant all the necessary privileges for the new user to connect to the database from your application.

      To begin, you need to access the MySQL client using the MySQL root account as shown here:

      You will be prompted to enter the root account password, set up during the prerequisite tutorial.

      Next, create a MySQL database for the application with:

      • CREATE DATABASE MovieAppDb;

      You will see the following output in the console:

      Output

      Query OK, 1 row affected (0.03 sec)

      You've now created the database successfully. Next, you will create a new MySQL user, associate them with the newly created database, and grant them all privileges.

      Run the following command to create the MySQL user and password. Remember to change the username and password to something more secure:

      • CREATE USER 'movie-admin'@'localhost' IDENTIFIED BY 'password';

      You will see the following output:

      Output

      Query OK, 0 rows affected (0.02 sec)

      To access a database or carry out a specific action on it, a MySQL user needs the appropriate permission. At the moment movie-admin does not have the appropriate permission over the application database.

      You will change that by running the following command to grant access to movie-admin on MovieAppDb:

      • GRANT ALL PRIVILEGES ON MovieAppDb.* TO 'movie-admin'@'localhost';

      You will see the following output:

      Output

      Query OK, 0 rows affected (0.01 sec)

      Now, you can reload the grant tables by running the following command to apply the changes that you just made using the flush statement:

      You will see the following output:

      Output

      Query OK, 0 rows affected (0.00 sec)

      You are done creating a new user and granting privileges. To test if you are on track, exit the MySQL client:

      Log in again, using the credentials of the MySQL user you just created and enter the appropriate password when prompted:

      Check to be sure that the user movie-admin can access the created database, check with:

      You will see the MovieAppDb table listed in the output:

      Output

      +--------------------+ | Database | +--------------------+ | MovieAppDb | | information_schema | +--------------------+ 2 rows in set (0.01 sec)

      Now, exit the MySQL client:

      You've created a database, made a new MySQL user for the demo application, and granted the newly created user the right privileges to access the database. In the next section, you will start setting up the demo application.

      Step 3 — Setting Up the Demo App and Database Credentials

      As stated earlier, you'll deploy an existing ASP.NET Core application. This application was built to create a movie list and it uses the Model-View-Controller design pattern to ensure a proper structure and separation of concerns. To create or add a new movie to the list, the user will populate the form fields with the appropriate details and click on the Create button to post the details to the controller. The controller at this point will receive a POST HTTP request with the submitted details and persist the data in the database through the model.

      You will use Git to pull the source code of this demo application from GitHub and save it in a new directory. You could also download an alternate application here if you will be deploying a different application.

      To begin, create a new directory named movie-app from the terminal by using the following command:

      • sudo mkdir -p /var/www/movie-app

      This will serve as the root directory for your application. Next, change the folder owner and group in order to allow a non-root user account to work with the project files:

      • sudo chown sammy:sammy /var/www/movie-app

      Replace sammy with your sudo non-root username.

      Now, you can move into the parent directory and clone the application on GitHub:

      • cd /var/www
      • git clone https://github.com/do-community/movie-app-list.git movie-app

      You will see the following output:

      Output

      Cloning into 'movie-app'... remote: Enumerating objects: 91, done. remote: Counting objects: 100% (91/91), done. remote: Compressing objects: 100% (73/73), done. remote: Total 91 (delta 13), reused 91 (delta 13), pack-reused 0 Unpacking objects: 100% (91/91), done.

      You have successfully cloned the demo application from GitHub, so the next step will be to create a successful connection to the application database. You will do this by editing the ConnectionStrings property within the appsettings.json file and add the details of the database.

      Change directory into the application:

      Now open the file for editing:

      • sudo nano appsettings.json

      Add your database credentials:

      appsettings.json

      {
        "Logging": {
          "LogLevel": {
            "Default": "Warning"
          }
        },
        "AllowedHosts": "*",
        "ConnectionStrings": {
          "MovieContext": "Server=localhost;User Id=movie-admin;Password=password;Database=MovieAppDb"
        }
      }
      

      With this in place, you've successfully created a connection to your database. Now press CTRL+X to save your changes to the file and type Y to confirm. Then hit ENTER to exit the page.

      ASP.NET Core applications use a .NET standard library named Entity Framework (EF) Core to manage interaction with the database. Entity Framework Core is a lightweight, cross-platform version of the popular Entity Framework data access technology. It is an object-relational mapper (ORM) that enables .NET developers to work with a database using any of the database providers, such as MySQL.

      You can now update your database with the tables from the cloned demo application. Run the following command for that purpose:

      • dotnet ef database update

      This will apply an update to the database and create the appropriate schemas.

      Now, to build the project and all its dependencies, run the following command:

      You will see output similar to:

      Output

      Microsoft (R) Build Engine version 16.1.76+g14b0a930a7 for .NET Core Copyright (C) Microsoft Corporation. All rights reserved. Restore completed in 95.09 ms for /var/www/movie-app/MvcMovie.csproj. MvcMovie -> /var/www/movie-app/bin/Debug/netcoreapp2.2/MvcMovie.dll MvcMovie -> /var/www/movie-app/bin/Debug/netcoreapp2.2/MvcMovie.Views.dll Build succeeded. 0 Warning(s) 0 Error(s) Time Elapsed 00:00:01.91

      This will build the project and install any third-party dependencies listed in the project.assets.json file but the application won’t be ready for production yet. To get the application ready for deployment, run the following command:

      You will see the following:

      Output

      Microsoft (R) Build Engine version 16.1.76+g14b0a930a7 for .NET Core Copyright (C) Microsoft Corporation. All rights reserved. Restore completed in 89.62 ms for /var/www/movie-app/MvcMovie.csproj. MvcMovie -> /var/www/movie-app/bin/Debug/netcoreapp2.2/MvcMovie.dll MvcMovie -> /var/www/movie-app/bin/Debug/netcoreapp2.2/MvcMovie.Views.dll MvcMovie -> /var/www/movie-app/bin/Debug/netcoreapp2.2/publish/

      This will pack and compile the application, read through its dependencies, publish the resulting set of files into a folder for deployment, and produce a cross-platform .dll file that uses the installed .NET Core runtime to run the application.

      By installing dependencies, creating a connection to the database, updating the database with the necessary tables, and publishing it for production, you've completed the setup for this demo application. In the next step you will configure the web server to make the application accessible and secure at your domain.

      Step 4 — Configuring the Web Server

      By now, having followed the How To Secure Nginx with Let's Encrypt tutorial, you'll have a server block for your domain at /etc/nginx/sites-available/your_domain with the server_name directive already set appropriately. In this step, you will edit this server block to configure Nginx as a reverse proxy for your application. A reverse proxy is a server that sits in front of web servers and forwards every web browser’s request to those web servers. It receives all requests from the network and forwards them to a different web server.

      In the case of an ASP.NET Core application, Kestrel is the preferred web server that is included with it by default. It is great for serving dynamic content from an ASP.NET Core application as it provides better request-processing performance and was designed to make ASP.NET as fast as possible. However, Kestrel isn't considered a full-featured web server because it can't manage security and serve static files, which is why it is advisable to always run it behind a web server.

      To begin, ensure that you are within the root directory of your server:

      Open the server block for editing with:

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

      As detailed in the Step 4 of the How To Secure Nginx with Let's Encrypt tutorial, if you selected option 2, Certbot will automatically configure this server block in order to redirect HTTP traffic to HTTPS with just a few modifications.

      Continue with the configuration by editing the first two blocks in the file to reflect the following:

      /etc/nginx/sites-available/your-domain

      server {
      
          server_name your-domain  www.your-domain;
      
         location / {
           proxy_pass http://localhost:5000;
           proxy_http_version 1.1;
           proxy_set_header Upgrade $http_upgrade;
           proxy_set_header Connection keep-alive;
           proxy_set_header Host $host;
           proxy_cache_bypass $http_upgrade;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_set_header X-Forwarded-Proto $scheme;
          }
      
      listen [::]:443 ssl ipv6only=on; # managed by Certbot
      listen 443 ssl; # managed by Certbot
      ssl_certificate /etc/letsencrypt/live/your-domain/fullchain.pem; # managed by Certbot
      ssl_certificate_key /etc/letsencrypt/live/your-domain/privkey.pem; # managed by Certbot
      include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
      ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
      
      
      }
      ...
      

      The configuration in this server block will instruct Nginx to listen on port 443, which is the standard port for websites that use SSL. Furthermore, Nginx will accept public traffic on port 443 and forward every matching request to the built-in Kestrel server at http://localhost:5000.

      Finally, following the server block you just edited in the file, ensure that the second server block looks like so:

      /etc/nginx/sites-available/your-domain

      
      ...
      server {
      if ($host = www.your-domain) {
          return 301 https://$host$request_uri;
      } # managed by Certbot
      
      
      if ($host = your-domain) {
          return 301 https://$host$request_uri;
      } # managed by Certbot
      
      
          listen 80;
          listen [::]:80;
      
          server_name your-domain  www.your-domain;
      return 404; # managed by Certbot
      }
      

      This server block will redirect all requests to https://your-domain and https://www.your-domain to a secure HTTPS access.

      Next, force Nginx to pick up the changes you've made to the server block by running:

      With the Nginx configuration successfully completed, the server is fully set up to forward all HTTPS requests made to https://your-domain on to the ASP.NET Core app running on Kestrel at http://localhost:5000. However, Nginx isn’t set up to manage the Kestrel server process. To handle this and ensure that the Kestrel process keeps running in the background, you will use systemd functionalities.

      Systemd files will allow you to manage a process by providing start, stop, restart, and log functionalities once you create a process of work called a unit.

      Move into the systemd directory:

      Create a new file for editing:

      Add the following content to it:

      movie.service

      [Unit]
      Description=Movie app
      
      [Service]
      WorkingDirectory=/var/www/movie-app
      ExecStart=/usr/bin/dotnet /var/www/movie-app/bin/Debug/netcoreapp2.2/publish/MvcMovie.dll
      Restart=always
      RestartSec=10
      SyslogIdentifier=movie
      User=sammy
      Environment=ASPNETCORE_ENVIRONMENT=Production
      Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
      
      [Install]
      WantedBy=multi-user.target
      

      The configuration file specifies the location of the project’s folder with WorkingDirectory and the command to execute at the start of the process in ExecStart. In addition, you've used the RestartSec directive to specify when to restart the systemd service if the .NET runtime service crashes.

      Now save the file and enable the new movie service created with:

      • sudo systemctl enable movie.service

      After that, proceed to start the service and verify that it’s running by starting the service:

      • sudo systemctl start movie.service

      Then check its status:

      • sudo systemctl status movie.service

      You will see the following output:

      Output

      movie.service - Movie app Loaded: loaded (/etc/systemd/system/movie.service; enabled; vendor preset: enabled) Active: active (running) since Sun 2019-06-23 04:51:28 UTC; 11s ago Main PID: 6038 (dotnet) Tasks: 16 (limit: 1152) CGroup: /system.slice/movie.service └─6038 /usr/bin/dotnet /var/www/movie-app/bin/Debug/netcoreapp2.2/publish/MvcMovie.dll

      This output gives you an overview of the current status of the movie.service created to keep your app running. It indicates that the service is enabled and currently active.

      Navigate to https://your-domain from your browser to run and test out the application.

      You'll see the home page for the demo application—Movie List Application.

      Movie list application

      With the reverse proxy configured and Kestrel managed through systemd, the web app is fully configured and can be accessed from a browser.

      Conclusion

      In this tutorial, you deployed an ASP.NET Core application to an Ubuntu server. To persist and manage data, you installed and used MySQL server and used the Nginx web server as a reverse proxy to serve your application.

      Beyond this tutorial, if you're interested in building an interactive web application using C# instead of Javascript you could try a web UI framework by Microsoft called Blazor. It is an event-driven component-based web UI for implementing logic on the client side of an ASP.NET Core application.

      If you wish to deploy your own application, you'll need to consider other required procedures to deploy your app. The complete source code for this demo application can be found here on GitHub.



      Source link