One place for hosting & domains

      November 2020

      How To Deploy a Django App on App Platform


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

      Introduction

      Django is a powerful web framework that allows you to deploy your Python applications or websites. Django includes many features such as authentication, a custom database ORM (Object-Relational Mapper), and an extensible plugin architecture. Django simplifies the complexities of web development, allowing you to focus on writing code.

      In this tutorial, you’ll configure a Django project and deploy it to DigitalOcean’s App Platform using GitHub.

      Prerequisites

      To complete this tutorial, you’ll need:

      Step 1 — Creating a Python Virtual Environment for your Project

      Before you get started, you need to set up our Python developer environment. You will install your Python requirements within a virtual environment for easier management.

      First, create a directory in your home directory that you can use to store all of your virtual environments:

      Now create your virtual environment using Python:

      • python3 -m venv ~/.venvs/django

      This will create a directory called django within your .venvs directory. Inside, it will install a local version of Python and a local version of pip. You can use this to install and configure an isolated Python environment for your project.

      Before you install your project’s Python requirements, you need to activate the virtual environment. You can do that by typing:

      • source ~.venvs/django/bin/activate

      Your prompt should change to indicate that you are now operating within a Python virtual environment. It will look something like this: (django)user@host:~$.

      With your virtual environment active, install Django, Gunicorn, whitenoise, dj-database-url, and the psycopg2 PostgreSQL adaptor with the local instance of pip:

      • pip install django gunicorn psycopg2-binary dj-database-url

      Note: When the virtual environment is activated (when your prompt has (django) preceding it), use pip instead of pip3, even if you are using Python 3. The virtual environment’s copy of the tool is always named pip, regardless of the Python version.

      These packages do the following:

      • django - Installs the Django framework and libraries
      • gunicorn - A tool for deploying Django with a WSGI
      • dj-database-url - A Django tool for parsing a database URL
      • psycopg2 - A PostgreSQL adapter that allows Django to connect to a PostgreSQL database

      Now that you have these packages installed, you will need to save these requirements and their dependencies so App Platform can install them later. You can do this using pip and saving the information to a requirements.txt file:

      • pip freeze > requirements.txt

      You should now have all of the software needed to start a Django project. You are almost ready to deploy.

      Step 2 — Creating the Django Project

      Create your project using the django-admin tool that was installed when you installed Django:

      • django-admin startproject django_app

      At this point, your current directory (django_app in your case) will have the following content:

      • manage.py: A Django project management script.
      • django_app/: The Django project package. This should contain the __init__.py, settings.py, urls.py, asgi.py, and wsgi.py files.

      This directory will be the root directory of your project and will be what we upload to GitHub. Navigate into this directory with the command:

      Let’s adjust some settings before deployment.

      Adjusting the Project Settings

      Now that you’ve created a Django project, you’ll need to modify the settings to ensure it will run properly in App Platform. Open the settings file in your text editor:

      • nano django_app/settings.py

      Let’s examine our configuration one step at a time.

      Reading Environment Variables

      First, you need to add the os import statement to be able to read environment variables:

      django_app/settings.py

      import os
      

      Setting the Secret Key

      Next, you need to modify the SECRET_KEY directive. This is set by Django on the initial project creation and will have a randomly generated default value. It is unsafe to keep this hardcoded value in the code once it’s pushed to GitHub, so you should either read this from an environment variable or generate it when the application is started. To do this, add the following import statement at the top of the settings file:

      django_app/settings.py

      from django.core.management.utils import get_random_secret_key
      

      Now modify the SECRET_KEY directive to read in the value from the environment variable DJANGO_SECRET_KEY or generate the key if it does not find said environment variable:

      django_app/settings.py

      SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key())
      

      Warning: If you don’t set this environment variable, then every time the app is re-deployed, this key will change. This can have adverse effects on cookies and will require users to log in again every time this key changes. You can generate a key using an online password generator.

      Setting Allowed Hosts

      Now locate the ALLOWED_HOSTS directive. This defines a list of the server’s addresses or domain names that may be used to connect to the Django instance. Any incoming request with a Host header that is not in this list will raise an exception. Django requires that you set this to prevent a certain class of security vulnerability.

      In the square brackets, list the IP addresses or domain names that are associated with your Django server. Each item should be listed in quotations with entries separated by a comma. If you wish requests for an entire domain and any subdomains, prepend a period to the beginning of the entry.

      App Platform supplies you with a custom URL as a default and then allows you to set a custom domain after you have deployed the application. Since you won’t know this custom URL until you have deployed the application, you should attempt to read the ALLOWED_HOSTS from an environment variable, so App Platform can inject this into your app when it launches.

      We’ll cover this process more in-depth in a later section. But for now, modify your ALLOWED_HOSTS directive to attempt to read the hosts from an environment variable. The environment variable can be set to either a single host or a comma-delimited list:

      django_app/settings.py

      ALLOWED_HOSTS = os.getenv("DJANGO_ALLOWED_HOSTS", "127.0.0.1,localhost").split(",")
      

      Setting the Debug Directive

      Next you should modify the DEBUG directive so that you can toggle this by setting an environment variable:

      django_app/settings.py

      DEBUG = os.getenv("DEBUG", "False") == "True"
      

      Here you used the getenv method to check for an environment variable named DEBUG. If this variable isn’t found, we should default to False for safety. Since environment variables will be read in as strings from App Platform, be sure to make a comparison to ensure that your variable is evaluated correctly.

      Setting the Development Mode

      Now create a new directive named DEVELOPMENT_MODE that will also be set as an environment variable. This is a helper variable that you will use to determine when to connect to your Postgres database and when to connect to a local SQLite database for testing. You’ll use this variable later when setting up the database connection:

      django_app/settings.py

      DEVELOPMENT_MODE = os.getenv("DEVELOPMENT_MODE", "False") == "True"
      

      Configuring Database Access

      Next, find the section that configures database access. It will start with DATABASES. The configuration in the file is for a SQLite database. App Platform allows you to create a PostgreSQL database for our project, so you need to adjust the settings to be able to connect to it.

      Warning: If you don’t change these settings and continue with the SQLite DB, your database will be erased after every new deployment. App Platform doesn’t maintain the disk when re-deploying applications, and your data will be lost.

      Change the settings with your PostgreSQL database information. You’ll read in the database connection information and credentials from an environment variable, DATABASE_URL, that will be provided by App Platform. Use the psycopg2 adaptor we installed with pip to have Django access a PostgreSQL database. You’ll use the dj-database-url package that was installed to get all of the necessary information from the database connection URL.

      To facilitate with development of your application locally, you’ll also use an if statement here to determine if DEVELOPMENT_MODE is set to True and which database should be accessed. By default, this will be set to False, and it will attempt to connect to a PostgreSQL database. You also don’t want Django attempting to make a database connection to the PostgreSQL database when attempting to collect the static files, so you’ll write an if statement to examine the command that was executed and not connect to a database if you determine that the command given was collectstatic. App Platform will automatically collect static files when the app is deployed.

      First, install the sys library so you can determine the command that was passed to manage.py and the dj_database_url library to be able to parse the URL passed in:

      django_app/settings.py

      . . .
      import os
      import sys
      import dj_database_url
      

      Next remove the current DATABASE directive block and replace it with this:

      django_app/settings.py

      if DEVELOPMENT_MODE is True:
          DATABASES = {
              "default": {
                  "ENGINE": "django.db.backends.sqlite3",
                  "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
              }
          }
      elif len(sys.argv) > 0 and sys.argv[1] != 'collectstatic':
          if os.getenv("DATABASE_URL", None) is None:
              raise Exception("DATABASE_URL environment variable not defined")
          DATABASES = {
              "default": dj_database_url.parse(os.environ.get("DATABASE_URL")),
          }
      
      

      Next, move down to the bottom of the file and add a setting indicating where the static files should be placed. When your Django app is deployed to App Platform, python manage.py collectstatic will be run automatically. Set the route to match the STATIC_URL directive in the settings file:

      django_app/settings.py

      . . .
      STATIC_URL = "/static/"
      STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
      

      Note: If you plan on storing static files in other locations outside of your individual Django-app static files, you will need to add an additional directive to your settings file. This directive will specify where to find these files. Be aware that these directories cannot share the same name as your STATIC_ROOT:

      django_app/settings.py

      . . .
      STATIC_URL = "/static/"
      STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
      STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"))
      

      Reviewing the Completed settings.py File

      Your completed file will look like this:

      from django.core.management.utils import get_random_secret_key
      from pathlib import Path
      import os
      import sys
      import dj_database_url
      
      # Build paths inside the project like this: BASE_DIR / 'subdir'.
      BASE_DIR = Path(__file__).resolve().parent.parent
      
      
      # Quick-start development settings - unsuitable for production
      # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
      
      # SECURITY WARNING: keep the secret key used in production secret!
      SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key())
      
      # SECURITY WARNING: don't run with debug turned on in production!
      DEBUG = os.getenv("DEBUG", "False") == "True"
      
      ALLOWED_HOSTS = os.getenv("DJANGO_ALLOWED_HOSTS", "127.0.0.1,localhost").split(",")
      
      
      # Application definition
      
      INSTALLED_APPS = [
          'django.contrib.admin',
          'django.contrib.auth',
          'django.contrib.contenttypes',
          'django.contrib.sessions',
          'django.contrib.messages',
          'django.contrib.staticfiles',
      ]
      
      MIDDLEWARE = [
          'django.middleware.security.SecurityMiddleware',
          'django.contrib.sessions.middleware.SessionMiddleware',
          'django.middleware.common.CommonMiddleware',
          'django.middleware.csrf.CsrfViewMiddleware',
          'django.contrib.auth.middleware.AuthenticationMiddleware',
          'django.contrib.messages.middleware.MessageMiddleware',
          'django.middleware.clickjacking.XFrameOptionsMiddleware',
          "whitenoise.middleware.WhiteNoiseMiddleware",
      ]
      
      ROOT_URLCONF = 'masons_django_app.urls'
      
      TEMPLATES = [
          {
              'BACKEND': 'django.template.backends.django.DjangoTemplates',
              'DIRS': [],
              'APP_DIRS': True,
              'OPTIONS': {
                  'context_processors': [
                      'django.template.context_processors.debug',
                      'django.template.context_processors.request',
                      'django.contrib.auth.context_processors.auth',
                      'django.contrib.messages.context_processors.messages',
                  ],
              },
          },
      ]
      
      WSGI_APPLICATION = 'masons_django_app.wsgi.application'
      
      
      # Database
      # https://docs.djangoproject.com/en/3.1/ref/settings/#databases
      DEVELOPMENT_MODE = os.getenv("DEVELOPMENT_MODE", "False") == "True"
      
      if DEVELOPMENT_MODE is True:
          DATABASES = {
              "default": {
                  "ENGINE": "django.db.backends.sqlite3",
                  "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
              }
          }
      elif len(sys.argv) > 0 and sys.argv[1] != 'collectstatic':
          if os.getenv("DATABASE_URL", None) is None:
              raise Exception("DATABASE_URL environment variable not defined")
          DATABASES = {
              "default": dj_database_url.parse(os.environ.get("DATABASE_URL")),
          }
      
      
      # Password validation
      # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
      
      AUTH_PASSWORD_VALIDATORS = [
          {
              'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
          },
          {
              'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
          },
          {
              'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
          },
          {
              'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
          },
      ]
      
      
      # Internationalization
      # https://docs.djangoproject.com/en/3.1/topics/i18n/
      
      LANGUAGE_CODE = 'en-us'
      
      TIME_ZONE = 'UTC'
      
      USE_I18N = True
      
      USE_L10N = True
      
      USE_TZ = True
      
      
      # Static files (CSS, JavaScript, Images)
      # https://docs.djangoproject.com/en/3.1/howto/static-files/
      
      STATIC_URL = "/static/"
      STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
      STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
      STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
      

      Save and close settings.py.

      You’ve now finished configuring your Django app to run on App Platform. Next, you’ll push the app to GitHub and deploy it to App Platform.

      Step 3 — Pushing the Site to GitHub

      DigitalOcean App Platform deploys your code from GitHub repositories, so the first thing you’ll need to do is get your site in a git repository and then push that repository to GitHub.

      First, initialize your Django project as a git repository:

      When you work on your Django app locally, certain files get added that are unnecessary for deployment. Let’s exclude that directory by adding it to Git’s ignore list. Create a new file called .gitignore:

      Now add the following code to the file:

      .gitignore

      db.sqlite3
      *.pyc
      

      Save and close the file.

      Now execute the following command to add files to your repository:

      • git add django_app/ manage.py requirements.txt static/

      Make your initial commit:

      • git commit -m "Initial Django App"

      Your files will commit:

      Output

      [master (root-commit) eda5d36] Initial Django App 8 files changed, 238 insertions(+) create mode 100644 django_app/__init__.py create mode 100644 django_app/asgi.py create mode 100644 django_app/settings.py create mode 100644 django_app/urls.py create mode 100644 django_app/wsgi.py create mode 100644 manage.py create mode 100644 requirements.txt create mode 100644 static/README.md

      Open your browser and navigate to GitHub, log in with your profile, and create a new repository called django-app. Create an empty repository without a README or license file.

      Once you’ve created the repository, return to the command line to push your local files to GitHub.

      First, add GitHub as a remote repository:

      • git remote add origin https://github.com/your_username/django-app

      Next, rename the default branch main, to match what GitHub expects:

      Finally, push your main branch to GitHub’s main branch:

      Your files will transfer:

      Output

      Enumerating objects: 12, done. Counting objects: 100% (12/12), done. Delta compression using up to 8 threads Compressing objects: 100% (9/9), done. Writing objects: 100% (12/12), 3.98 KiB | 150.00 KiB/s, done. Total 12 (delta 1), reused 0 (delta 0) remote: Resolving deltas: 100% (1/1), done. To github.com:yourUsername/django-app.git * [new branch] main -> main Branch 'main' set up to track remote branch 'main' from 'origin'.

      Enter your GitHub credentials when prompted to push your code.

      Your code is now on GitHub and accessible through a web browser. Now you will deploy your site to DigitalOcean’s App Platform.

      Step 4 — Deploying to DigitalOcean with App Platform

      Once the code is pushed, visit https://cloud.digitalocean.com/apps and click Launch Your App. You’ll be prompted to connect your GitHub account:

      Connect GitHub account

      Connect your account and allow DigitalOcean to access your repositories. You can choose to let DigitalOcean have access to all of your repositories or just to the ones you wish to deploy.

      Allow repository access

      Click Install and Authorize. You’ll be returned to your DigitalOcean dashboard to continue creating your app.

      Once your GitHub account is connected, select the your_account/django-app repository and click Next.

      Choose your repository

      Next, provide your app’s name, choose a region, and ensure the main branch is selected. Then ensure that Autodeploy code changes is checked. Click Next to continue.

      Choose a name, region, and branch

      DigitalOcean will detect that your project is a Python app and will automatically populate a partial run command.

      Python Application detected and partial run command populated

      Click the Edit link next to the Build and Run commands to complete the build command. Your completed build command needs to reference your project’s WSGI file. In this example, this is at django_app.wsgi. Your completed run command should be gunicorn --worker-tmp-dir /dev/shm django_app.wsgi.

      Completing the run command

      Next, you need to define the environment variables you declared in your project’s settings. App Platform has a concept of App-Wide Variables, which are environment variables that are provided by App Platform, such as APP_URL and APP_DOMAIN. The platform also maintains Component-Specific Variables, which are variables that are exported from your components. These will be useful for determining your APP_DOMAIN beforehand so you can properly set DJANGO_ALLOWED_HOSTS. You will also use these variables to copy configuration settings from your database.

      To read more about these different variables, consult the App Platform Environment Variable Documetation

      For your Django app to function, you need to set the following environment variables like so:

      • DJANGO_ALLOWED_HOSTS -> ${APP_DOMAIN}
        • This allows us to know the randomly generated URL that App Platform provides and provide it to our app
      • DATABASE_URL -> ${<NAME_OF_YOUR_DATABASE>.DATABASE_URL}
        • In this case, we’ll name our database db in the next step, so this should be ${db.DATABASE_URL}
      • DEBUG -> True
        • Set this to True for now to verify your app is functioning and set to False when it’s time for this app to be in production
      • DJANGO_SECRET_KEY -> <A RANDOM SECRET KEY>
        • You can either allow your app to generate this at every launch or pick a strong password with at least 32 characters to use as this key. Using a secure password generator is a good option for this
        • Don’t forget to click the Encrypt check box to ensure that your credentials are encrypted for safety

      Set environment variables

      To set up your database, click the Add a Database button. You will be presented with the option of selecting a small development database or integrating with a managed database elsewhere. For this deployment, select the development database and ensure that the name of the database is db. Once you’ve verified this, click the Add Database button.

      Add a database

      Click Next, and you’ll be directed to the Finalize and Launch screen where you’ll choose your plan. Be sure to select the appropriate plan to fit your needs, whether in Basic App or Professional App and then click Launch App at the bottom. Your app will build and deploy:

      App building and deploying

      Once the build process completes, the interface will show you a healthy site. Now you need to access your app’s console through the Console tab and perform the Django first launch tasks by running the following commands:

      • python manage.py migrate - This will perform your initial database migrations.
      • python manage.py createsuperuser - This will prompt you for some information to create an administrative user

      Perform initial Django tasks

      Once you are done with that, click on the link to your app provided by App Platform:

      Click on app link

      This link should take you to the standard initial Django page.

      Initial Django Page

      And now you have a Django app deployed to App Platform. Any changes that you make and push to GitHub will be automatically deployed.

      Step 5 — Deploying Your Static Files

      Now that you’ve deployed your app, you may notice that your static files aren’t being loaded if you have DEBUG set to False. Django doesn’t serve static files in production and instead wants you to deploy them using a web server or CDN. Luckily, App Platform can do just that. App Platform provides free static asset serving if you are running a service alongside it, as you are doing with your app. So you’re going to deploy your same Django app but as a static site this time.

      Once your app is deployed, add a static site component from the Components tab in your app.

      Add Static Site

      Select the same GitHub repository as your deployed Django service. Click Next to continue.

      Select GitHub Repo

      Next, provide your app’s name and ensure the main branch is selected. Click Next to continue.

      Set Static Site Name and Branch

      Your component will be detected as a Service, so you’ll want to change the type to Static Site. Essentially we’ll have Django gather our static files and serve them. Set the route to what you set your STATIC_URL directive in your settings file. We set our directive to /static/ so set the route to /static. Finally, your static files will be collected into Output Directory in your app to match your STATIC_ROOT setting in settings.py. Yours is set to staticfiles, so set Output Directory to that.

      Static Site Settings

      Click Next, and you’ll be directed to the Finalize and Launch screen. When static files are paired with a service, it is free, so you won’t see any change in your bill. Click Launch App and deploy your static files. Now, if you have Debug set to False, you’ll see your static files properly displayed. Note that this tutorial’s only static asset is a README.md file. You will likely have more than this.

      Conclusion

      In this tutorial, you set up a Django project and deployed it using DigitalOcean’s App Platform. Any changes you commit and push to your repository will be re-deployed, so you can now expand your application. You can find the example code for this tutorial in the DigitalOcean Sample Images Repository

      The example in this tutorial is a minimal Django project. Your app might have more applications and features, but the deployment process will be the same.



      Source link

      How to Install WordPress with LEMP on Ubuntu 20.04


      Introduction

      WordPress, one of the most popular content management systems (CMS) on the internet currently, allows users to set up flexible blogs and websites using a MySQL backend with PHP processing. WordPress has seen an incredible adoption rate among new and experienced engineers alike, and is a great choice for getting a website up and running efficiently. After an initial setup, almost all administration for WordPress websites can be done through its graphical interface— these features and more make WordPress a great choice for websites built to scale.

      In this tutorial, you’ll focus on getting an instance of WordPress set up on a LEMP stack (Linux, Nginx, MySQL, and PHP) for an Ubuntu 20.04 server.

      Prerequisites

      In order to complete this tutorial, you’ll need access to an Ubuntu 20.04 server. To successfully install WordPress with LEMP on your server, you’ll also need to perform the following tasks before starting this tutorial:

      • Create a sudo user on your server: The steps in this tutorial are using a non-root user with sudo privileges. You can create a user with sudo privileges by following our Ubuntu 20.04 initial server setup tutorial.
      • Install a LEMP stack: WordPress will need a web server, a database, and PHP in order to correctly function. Setting up a LEMP stack (Linux, Nginx, MySQL, and PHP) fulfills all of these requirements. Follow this tutorial to install and configure this software.

      Rather than setting up these components yourself, you can quickly provision Ubuntu 20.04 server that already has a LEMP stack installed with DigitalOcean’s LEMP 1-click install app.

      Be aware, though, that this tutorial still assumes you have an administrative sudo user and an Nginx server block configured on your server. Even with a server provisioned with the LEMP 1-click app, you’ll need to follow Steps 1, 2, 3, and 5 of our Ubuntu 20.04 initial server setup tutorial. You’ll also need to complete Step 4 of our guide on installing the LEMP Stack on Ubuntu 20.04 to configure an Nginx server block and configure Nginx to use the PHP Processor

      • Secure your site with SSL: WordPress serves dynamic content and handles user authentication and authorization. TLS/SSL is the technology that allows you to encrypt the traffic from your site so that your connection is secure. The way you set up SSL will depend on whether you have a domain name for your site.
        • If you have a domain name, the easiest way to secure your site is with Let’s Encrypt, which provides free, trusted certificates. Follow our Let’s Encrypt guide for Nginx to set this up.
        • If you do not have a domain and you’re using this configuration for testing or personal use, you can use a self-signed certificate instead. This provides the same type of encryption, but without the domain validation. Follow our self-signed SSL guide for Nginx to get set up.

      When you are finished with setup, log in to your server as the sudo user to continue.

      Step 1 — Creating a MySQL Database and User for WordPress

      WordPress uses MySQL to manage and store site and user information. Although you already have MySQL installed, let’s create a database and a user for WordPress to use.

      To get started, log in to the MySQL root (administrative) account. If MySQL is configured to use the auth_socket authentication plugin (which is default), you can log in to the MySQL administrative account using sudo:

      If you have changed the authentication method to use a password for the MySQL root account, use the following command instead:

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

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

      • CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

      Note: Every MySQL statement must end in a semi-colon (;). If you’ve encountered an error, check to make sure the semicolon is present.

      Next, let’s create a separate MySQL user account that we will use exclusively to operate on our new database. Creating single-purpose databases and accounts is a good idea from a management and security standpoint. We’ll use the name wordpressuser in this guide — feel free to change this if you’d like.

      In the following command, you are going to create an account, set a password, and grant access to the database you created. Remember to choose a strong password here:

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

      You now have a database and user account, each made specifically for WordPress.

      With the database tasks complete, let’s exit out of MySQL by typing:

      The MySQL session will exit, returning you to the regular Linux shell.

      Step 2 — Installing Additional PHP Extensions

      When setting up the LEMP stack, it required a very minimal set of extensions to get PHP to communicate with MySQL. WordPress and many of its plugins leverage additional PHP extensions, and you’ll use a few more in this tutorial.

      Let’s download and install some of the most popular PHP extensions for use with WordPress by typing:

      • sudo apt install php-curl php-gd php-intl php-mbstring php-soap php-xml php-xmlrpc php-zip

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

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

      • sudo systemctl restart php7.4-fpm

      You now have all of the PHP extensions needed, installed on the server.

      Step 3 — Configuring Nginx

      Next, let’s make a few adjustments to our Nginx server block files. Based on the prerequisite tutorials, you should have a configuration file for your site in the /etc/nginx/sites-available/ directory configured to respond to your server’s domain name or IP address and protected by a TLS/SSL certificate. We’ll use /etc/apache2/sites-available/wordpress as an example here, but you should substitute the path to your configuration file where appropriate.

      Additionally, we will use /var/www/wordpress as the root directory of our WordPress install in this guide. Again, you should use the web root specified in your own configuration.

      Note: It’s possible you are using the /etc/nginx/sites-available/default default configuration (with /var/www/html as your web root). This is fine to use if you’re only going to host one website on this server. If not, it’s best to split the necessary configuration into logical chunks, one file per site.

      Open your site’s server block file with sudo privileges to begin:

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

      Within the main server block, let’s add a few location blocks.

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

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

      /etc/nginx/sites-available/wordpress

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

      Inside of the existing location / block, let’s adjust the try_files list. Comment out the default setting by prepending the line with a pound sign (#) and then add the highlighted line. This way, instead of returning a 404 error as the default option, control is passed to the index.php file with the request arguments.

      This should look something like this:

      /etc/nginx/sites-available/wordpress

      server {
          . . .
          location / {
              #try_files $uri $uri/ =404;
              try_files $uri $uri/ /index.php$is_args$args;
          }
          . . .
      }
      

      When you are finished, save and close the file.

      Now, let’s check our configuration for syntax errors by typing:

      If no errors were reported, reload Nginx by typing:

      • sudo systemctl reload nginx

      Next, let’s download and set up WordPress.

      Step 4 — Downloading WordPress

      Now that your server software is configured, let’s download and set up WordPress. For security reasons, it is always recommended to get the latest version of WordPress directly from the project’s website.

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

      This changes your directory to the temporary folder. Then, enter the following command to download the latest version of WordPress in a compressed file:

      • curl -LO https://wordpress.org/latest.tar.gz

      Note: The -LO flag is used to get directly to the source of the compressed file. -L ensures that fetching the file is successful in the case of redirects, and -O writes the output of our remote file with a local file that has the same name. To learn more about curl commands, visit How to Download Files with cURL

      Extract the compressed file to create the WordPress directory structure:

      You will be moving these files into our document root momentarily, but before you do, let’s copy over the sample configuration file to the filename that WordPress actually reads:

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

      Now, let’s copy the entire contents of the directory into our document root. We’re using the -a flag to make sure our permissions are maintained, and a dot at the end of our source directory to indicate that everything within the directory should be copied (including hidden files):

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

      Now that our files are in place, you’ll assign ownership to the www-data user and group. This is the user and group that Nginx runs as, and Nginx will need to be able to read and write WordPress files in order to serve the website and perform automatic updates:

      • sudo chown -R www-data:www-data /var/www/wordpress

      Files are now in the server’s document root and have the correct ownership, but you still need to complete some additional configuration.

      Step 5 — Setting up the WordPress Configuration File

      Next, let’s make some changes to the main WordPress configuration file.

      When you open the file, you’ll start by adjusting some secret keys to provide some security for our installation. WordPress provides a secure generator for these values so that you don’t have to come up with values on your own. These are only used internally, so it won’t hurt usability to have complex, secure values here.

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

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

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

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

      Output

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

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

      Now, open the WordPress configuration file:

      • sudo nano /var/www/wordpress/wp-config.php

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

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

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

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

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

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

      Next, let’s modify some of the database connection settings at the beginning of the file. You’ll have to adjust the database name, the database user, and the associated password that was configured within MySQL.

      The other change you should make is to set the method that WordPress uses to write to the filesystem. Since you’ve given the web server permission to write where it needs to, you can explicitly set the filesystem method to “direct”. Failure to set this with our current settings would result in WordPress prompting for FTP credentials when we perform some actions. Add this setting below the database connection settings, or anywhere else in the file:

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

      . . .
      
      define( 'DB_NAME', 'wordpress' );
      
      /** MySQL database username */
      define( 'DB_USER', 'wordpressuser' );
      
      /** MySQL database password */
      define( 'DB_PASSWORD', 'password' );
      
      . . .
      
      define( 'FS_METHOD', 'direct' );
      

      Save and close the file when you’re done.

      Step 6 — Completing the Installation Through the Web Interface

      Now that the server configuration is complete, you can finish up the installation through WordPress’ web interface.

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

      http://server_domain_or_IP/wordpress
      

      Select the language you would like to use:

      WordPress language selection

      Next, you will come to the main setup page.

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

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

      WordPress setup installation

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

      WordPress login prompt

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

      WordPress login prompt

      Conclusion

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

      If you’re looking for a one-click solution to install a WordPress Droplet, learn more about the WordPress One-Click App.



      Source link

      Dealing With Latency in Real-Time Online Multiplayer Video Games


      How to Join

      This Tech Talk is free and open to everyone. Register on Eventbrite here to receive a link to join on Thursday, December 10, 2020, 11:00–12:00 p.m. ET.

      About the Talk

      Multiplayer video games have been growing in popularity for decades. Online video games, in particular, are a great way to have fun with friends and family from all over the world. But how do online multiplayer games work, and what sorts of challenges are encountered by game developers? Whether you’re interested in making your own game or just eager to learn about some of the techniques used to overcome these challenges, this talk is for you!

      What You’ll Learn

      • The basics of how video games work
      • How latency affects games
      • Ways we can mitigate the effects of latency

      This Talk is Designed For

      Anyone who is interested in online video games. Programming knowledge isn’t strictly necessary, but there may be one or two more technical terms used throughout the talk.

      About the Presenter

      Julian Miller is a senior software engineer at DigitalOcean who has always loved video games. He feels lucky to have had the opportunity to work on AAA titles in the past.

      To join the live Tech Talk, register here.



      Source link