One place for hosting & domains

      Application

      How To Build a Node.js Application with Docker


      Introduction

      The Docker platform allows developers to package and run applications as containers. A container is an isolated process that runs on a shared operating system, offering a lighter weight alternative to virtual machines. Though containers are not new, they offer benefits — including process isolation and environment standardization — that are growing in importance as more developers use distributed application architectures.

      When building and scaling an application with Docker, the starting point is typically creating an image for your application, which you can then run in a container. The image includes your application code, libraries, configuration files, environment variables, and runtime. Using an image ensures that the environment in your container is standardized and contains only what is necessary to build and run your application.

      In this tutorial, you will create an application image for a static website that uses the Express framework and Bootstrap. You will then build a container using that image and push it to Docker Hub for future use. Finally, you will pull the stored image from your Docker Hub repository and build another container, demonstrating how you can recreate and scale your application.

      Prerequisites

      To follow this tutorial, you will need:

      Step 1 — Installing Your Application Dependencies

      To create your image, you will first need to make your application files, which you can then copy to your container. These files will include your application’s static content, code, and dependencies.

      First, create a directory for your project in your non-root user’s home directory. We will call ours node_project, but you should feel free to replace this with something else:

      Navigate to this directory:

      This will be the root directory of the project.

      Next, create a package.json file with your project's dependencies and other identifying information. Open the file with nano or your favorite editor:

      Add the following information about the project, including its name, author, license, entrypoint, and dependencies. Be sure to replace the author information with your own name and contact details:

      ~/node_project/package.json

      {
        "name": "nodejs-image-demo",
        "version": "1.0.0",
        "description": "nodejs image demo",
        "author": "Sammy the Shark <sammy@example.com>",
        "license": "MIT",
        "main": "app.js",
        "scripts": {
          "start": "node app.js",
          "test": "echo "Error: no test specified" && exit 1"
        },
        "keywords": [
          "nodejs",
          "bootstrap",
          "express"
        ],
        "dependencies": {
          "express": "^4.16.4"
        }
      }
      

      This file includes the project name, author, and license under which it is being shared. Npm recommends making your project name short and descriptive, and avoiding duplicates in the npm registry. We've listed the MIT license in the license field, permitting the free use and distribution of the application code.

      Additionally, the file specifies:

      • "main": The entrypoint for the application, app.js. You will create this file next.
      • "scripts": The commands that will run when you use npm start to start your application.
      • "dependencies": The project dependencies — in this case, Express 4.16.4 or above.

      Though this file does not list a repository, you can add one by following these guidelines on adding a repository to your package.json file. This is a good addition if you are versioning your application.

      Save and close the file when you've finished making changes.

      To install your project's dependencies, run the following command:

      This will install the packages you've listed in your package.json file in your project directory.

      We can now move on to building the application files.

      Step 2 — Creating the Application Files

      We will create a website that offers users information about sharks. Our application will have a main entrypoint, app.js, and a views directory that will include the project's static assets. The landing page, index.html, will offer users some preliminary information and a link to a page with more detailed shark information, sharks.html. In the views directory, we will create both the landing page and sharks.html.

      First, open app.js in the main project directory to define the project's routes:

      The first part of the file will create the Express application and Router objects, and define the base directory, port, and host as variables:

      ~/node_project/app.js

      var express = require("express");
      var app = express();
      var router = express.Router();
      
      var path = __dirname + '/views/';
      const PORT = 8080;
      const HOST = '0.0.0.0';
      

      The require function loads the express module, which we then use to create the app and router objects. The router object will perform the routing function of the application, and as we define HTTP method routes we will add them to this object to define how our application will handle requests.

      This section of the file also sets a few variables, path, PORT, and HOST:

      • path: Defines the base directory, which will be the views subdirectory within the current project directory.
      • HOST: Defines the address that the application will bind to and listen on. Setting this to 0.0.0.0 or all IPv4 addresses corresponds with Docker's default behavior of exposing containers to 0.0.0.0 unless otherwise instructed.
      • PORT: Tells the app to listen on and bind to port 8080.

      Next, set the routes for the application using the router object:

      ~/node_project/app.js

      ...
      
      router.use(function (req,res,next) {
        console.log("/" + req.method);
        next();
      });
      
      router.get("/",function(req,res){
        res.sendFile(path + "index.html");
      });
      
      router.get("/sharks",function(req,res){
        res.sendFile(path + "sharks.html");
      });
      

      The router.use function loads a middleware function that will log the router's requests and pass them on to the application's routes. These are defined in the subsequent functions, which specify that a GET request to the base project URL should return the index.html page, while a GET request to the /sharks route should return sharks.html.

      Finally, mount the router middleware and the application's static assets and tell the app to listen on port 8080:

      ~/node_project/app.js

      ...
      
      app.use(express.static(path));
      app.use("/", router);
      
      app.listen(8080, function () {
        console.log('Example app listening on port 8080!')
      })
      

      The finished app.js file will look like this:

      ~/node_project/app.js

      var express = require("express");
      var app = express();
      var router = express.Router();
      
      var path = __dirname + '/views/';
      const PORT = 8080;
      const HOST = '0.0.0.0';
      
      router.use(function (req,res,next) {
        console.log("/" + req.method);
        next();
      });
      
      router.get("/",function(req,res){
        res.sendFile(path + "index.html");
      });
      
      router.get("/sharks",function(req,res){
        res.sendFile(path + "sharks.html");
      });
      
      app.use(express.static(path));
      app.use("/", router);
      
      app.listen(8080, function () {
        console.log('Example app listening on port 8080!')
      })
      

      Save and close the file when you are finished.

      Next, let's add some static content to the application. Start by creating the views directory:

      Open the landing page file, index.html:

      Add the following code to the file, which will import Boostrap and create a jumbotron component with a link to the more detailed sharks.html info page:

      ~/node_project/views/index.html

      <!DOCTYPE html>
      <html lang="en">
         <head>
            <title>About Sharks</title>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
            <link href="css/styles.css" rel="stylesheet">
            <link href='https://fonts.googleapis.com/css?family=Merriweather:400,700' rel='stylesheet' type='text/css'>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
         </head>
         <body>
            <nav class="navbar navbar-inverse navbar-static-top">
               <div class="container">
                  <div class="navbar-header">
                     <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                     <span class="sr-only">Toggle navigation</span>
                     <span class="icon-bar"></span>
                     <span class="icon-bar"></span>
                     <span class="icon-bar"></span>
                     </button>
                     <a class="navbar-brand" href="#">Everything Sharks</a>
                  </div>
                  <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                     <ul class="nav navbar-nav mr-auto">
                        <li class="active"><a href="/">Home</a></li>
                        <li><a href="http://www.digitalocean.com/sharks">Sharks</a></li>
                     </ul>
                  </div>
               </div>
            </nav>
            <div class="jumbotron">
               <div class="container">
                  <h1>Want to Learn About Sharks?</h1>
                  <p>Are you ready to learn about sharks?</p>
                  <br>
                  <p><a class="btn btn-primary btn-lg" href="http://www.digitalocean.com/sharks" role="button">Get Shark Info</a></p>
               </div>
            </div>
            <div class="container">
               <div class="row">
                  <div class="col-md-6">
                     <h3>Not all sharks are alike</h3>
                     <p>Though some are dangerous, sharks generally do not attack humans. Out of the 500 species known to researchers, only 30 have been known to attack humans.</p>
                  </div>
                  <div class="col-md-6">
                     <h3>Sharks are ancient</h3>
                     <p>There is evidence to suggest that sharks lived up to 400 million years ago.</p>
                  </div>
               </div>
            </div>
         </body>
      </html>
      

      The top-level navbar here allows users to toggle between the Home and Sharks pages. In the navbar-nav subcomponent, we are using Bootstrap's active class to indicate the current page to the user. We've also specified the routes to our static pages, which match the routes we defined in app.js:

      ~/node_project/views/index.html

      ...
      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav mr-auto">
              <li class="active"><a href="/">Home</a></li>
              <li><a href="http://www.digitalocean.com/sharks">Sharks</a></li>
          </ul>
      </div>
      ...
      

      Additionally, we've created a link to our shark information page in our jumbotron's button:

      ~/node_project/views/index.html

      ...
      <div class="jumbotron">
          <div class="container">
            <h1>Want to Learn About Sharks?</h1>
            <p>Are you ready to learn about sharks?</p>
            <br>
            <p><a class="btn btn-primary btn-lg" href="http://www.digitalocean.com/sharks" role="button">Get Shark Info</a></p>
          </div>
      </div>
      ...
      

      There is also a link to a custom style sheet in the header:

      ~/node_project/views/index.html

      ...
      <link href="css/styles.css" rel="stylesheet">
      ...
      

      We will create this style sheet at the end of this step.

      Save and close the file when you are finished.

      With the application landing page in place, we can create our shark information page, sharks.html, which will offer interested users more information about sharks.

      Open the file:

      Add the following code, which imports Bootstrap and the custom style sheet and offers users detailed information about certain sharks:

      ~/node_project/views/sharks.html

      <!DOCTYPE html>
      <html lang="en">
         <head>
            <title>About Sharks</title>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
            <link href="css/styles.css" rel="stylesheet">
            <link href='https://fonts.googleapis.com/css?family=Merriweather:400,700' rel='stylesheet' type='text/css'>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
         </head>
         <nav class="navbar navbar-inverse navbar-static-top">
            <div class="container">
               <div class="navbar-header">
                  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                  <span class="sr-only">Toggle navigation</span>
                  <span class="icon-bar"></span>
                  <span class="icon-bar"></span>
                  <span class="icon-bar"></span>
                  </button>
                  <a class="navbar-brand" href="/">Everything Sharks</a>
               </div>
               <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                  <ul class="nav navbar-nav mr-auto">
                     <li><a href="/">Home</a></li>
                     <li class="active"><a href="http://www.digitalocean.com/sharks">Sharks</a></li>
                  </ul>
               </div>
            </div>
         </nav>
         <div class="jumbotron text-center">
            <h1>Shark Info</h1>
         </div>
         <div class="container">
            <div class="row">
               <div class="col-md-6">
                  <p>
                  <div class="caption">Some sharks are known to be dangerous to humans, though many more are not. The sawshark, for example, is not considered a threat to humans.</div>
                  <img src="https://assets.digitalocean.com/articles/docker_node_image/sawshark.jpg" alt="Sawshark">
                  </p>
               </div>
               <div class="col-md-6">
                  <p>
                  <div class="caption">Other sharks are known to be friendly and welcoming!</div>
                  <img src="https://assets.digitalocean.com/articles/docker_node_image/sammy.png" alt="Sammy the Shark">
                  </p>
               </div>
            </div>
          </div>
         </body>
      </html>
      

      Note that in this file, we again use the active class to indicate the current page.

      Save and close the file when you are finished.

      Finally, create the custom CSS style sheet that you've linked to in index.html and sharks.html by first creating a css folder in the views directory:

      Open the style sheet:

      • nano views/css/styles.css

      Add the following code, which will set the desired color and font for our pages:

      ~/node_project/views/css/styles.css

      .navbar {
          margin-bottom: 0;
      }
      
      body {
          background: #020A1B;
          color: #ffffff;
          font-family: 'Merriweather', sans-serif;
      }
      
      h1,
      h2 {
          font-weight: bold;
      }
      
      p {
          font-size: 16px;
          color: #ffffff;
      }
      
      .jumbotron {
          background: #0048CD;
          color: white;
          text-align: center;
      }
      
      .jumbotron p {
          color: white;
          font-size: 26px;
      }
      
      .btn-primary {
          color: #fff;
          text-color: #000000;
          border-color: white;
          margin-bottom: 5px;
      }
      
      img,
      video,
      audio {
          margin-top: 20px;
          max-width: 80%;
      }
      
      div.caption: {
          float: left;
          clear: both;
      }
      

      In addition to setting font and color, this file also limits the size of the images by specifying a max-width of 80%. This will prevent them from taking up more room than we would like on the page.

      Save and close the file when you are finished.

      With the application files in place and the project dependencies installed, you are ready to start the application.

      If you followed the initial server setup tutorial in the prerequisites, you will have an active firewall permitting only SSH traffic. To permit traffic to port 8080 run:

      To start the application, make sure that you are in your project's root directory:

      Start the application with npm start:

      Navigate your browser to http://your_server_ip:8080. You will see the following landing page:

      Application Landing Page

      Click on the Get Shark Info button. You will see the following information page:

      Shark Info Page

      You now have an application up and running. When you are ready, quit the server by typing CTRL+C. We can now move on to creating the Dockerfile that will allow us to recreate and scale this application as desired.

      Step 3 — Writing the Dockerfile

      Your Dockerfile specifies what will be included in your application container when it is executed. Using a Dockerfile allows you to define your container environment and avoid discrepancies with dependencies or runtime versions.

      Following these guidelines on building optimized containers, we will make our image as efficient as possible by minimizing the number of image layers and restricting the image's function to a single purpose — recreating our application files and static content.

      In your project's root directory, create the Dockerfile:

      Docker images are created using a succession of layered images that build on one another. Our first step will be to add the base image for our application that will form the starting point of the application build.

      Let's use the node:10 image, since, at the time of writing, this is the recommended LTS version of Node.js. Add the following FROM instruction to set the application's base image:

      ~/node_project/Dockerfile

      FROM node:10
      

      This image includes Node.js and npm. Each Dockerfile must begin with a FROM instruction.

      By default, the Docker Node image includes a non-root node user that you can use to avoid running your application container as root. It is a recommended security practice to avoid running containers as root and to restrict capabilities within the container to only those required to run its processes. We will therefore use the node user's home directory as the working directory for our application and set them as our user inside the container. For more information about best practices when working with the Docker Node image, see this best practices guide.

      To fine-tune the permissions on our application code in the container, let's create the node_modules subdirectory in /home/node along with the app directory. Creating these directories will ensure that they have the permissions we want, which will be important when we create local node modules in the container with npm install. In addition to creating these directories, we will set ownership on them to our node user:

      ~/node_project/Dockerfile

      ...
      RUN mkdir -p /home/node/app/node_modules && chown -R node:node /home/node/app
      

      For more information on the utility of consolidating RUN instructions, see this discussion of how to manage container layers.

      Next, set the working directory of the application to /home/node/app:

      ~/node_project/Dockerfile

      ...
      WORKDIR /home/node/app
      

      If a WORKDIR isn't set, Docker will create one by default, so it's a good idea to set it explicitly.

      Next, copy the package.json and package-lock.json (for npm 5+) files:

      ~/node_project/Dockerfile

      ...
      COPY package*.json ./
      

      Adding this COPY instruction before running npm install or copying the application code allows us to take advantage of Docker's caching mechanism. At each stage in the build, Docker will check to see if it has a layer cached for that particular instruction. If we change package.json, this layer will be rebuilt, but if we don't, this instruction will allow Docker to use the existing image layer and skip reinstalling our node modules.

      After copying the project dependencies, we can run npm install:

      ~/node_project/Dockerfile

      ...
      RUN npm install
      

      Copy your application code to the working application directory on the container:

      ~/node_project/Dockerfile

      ...
      COPY . .
      

      To ensure that the application files are owned by the non-root node user, copy the permissions from your application directory to the directory on the container:

      ~/node_project/Dockerfile

      ...
      COPY --chown=node:node . .
      

      Set the user to node:

      ~/node_project/Dockerfile

      ...
      USER node
      

      Expose port 8080 on the container and start the application:

      ~/node_project/Dockerfile

      ...
      EXPOSE 8080
      
      CMD [ "npm", "start" ]
      

      EXPOSE does not publish the port, but instead functions as a way of documenting which ports on the container will be published at runtime. CMD runs the command to start the application — in this case, npm start. Note that there should only be one CMD instruction in each Dockerfile. If you include more than one, only the last will take effect.

      There are many things you can do with the Dockerfile. For a complete list of instructions, please refer to Docker's Dockerfile reference documentation.

      The complete Dockerfile looks like this:

      ~/node_project/Dockerfile

      
      FROM node:10
      
      RUN mkdir -p /home/node/app/node_modules && chown -R node:node /home/node/app
      
      WORKDIR /home/node/app
      
      COPY package*.json ./
      
      RUN npm install
      
      COPY . .
      
      COPY --chown=node:node . .
      
      USER node
      
      EXPOSE 8080
      
      CMD [ "npm", "start" ]
      

      Save and close the file when you are finished editing.

      Before building the application image, let's add a .dockerignore file. Working in a similar way to a .gitignore file, .dockerignore specifies which files and directories in your project directory should not be copied over to your container.

      Open the .dockerignore file:

      Inside the file, add your local node modules, npm logs, Dockerfile, and .dockerignore file:

      ~/node_project/.dockerignore

      node_modules
      npm-debug.log
      Dockerfile
      .dockerignore
      

      If you are working with Git then you will also want to add your .git directory and .gitignore file.

      Save and close the file when you are finished.

      You are now ready to build the application image using the docker build command. Using the -t flag with docker build will allow you to tag the image with a memorable name. Because we are going to push the image to Docker Hub, let's include our Docker Hub username in the tag. We will tag the image as nodejs-image-demo, but feel free to replace this with a name of your own choosing. Remember to also replace your_dockerhub_username with your own Docker Hub username:

      • docker build -t your_dockerhub_username/nodejs-image-demo .

      The . specifies that the build context is the current directory.

      It will take a minute or two to build the image. Once it is complete, check your images:

      You will see the following output:

      Output

      REPOSITORY TAG IMAGE ID CREATED SIZE your_dockerhub_username/nodejs-image-demo latest 1c723fb2ef12 8 seconds ago 895MB node 10 f09e7c96b6de 17 hours ago 893MB

      It is now possible to create a container with this image using docker run. We will include three flags with this command:

      • -p: This publishes the port on the container and maps it to a port on our host. We will use port 80 on the host, but you should feel free to modify this as necessary if you have another process running on that port. For more information about how this works, see this discussion in the Docker docs on port binding.
      • -d: This runs the container in the background.
      • --name: This allows us to give the container a memorable name.

      Run the following command to build the container:

      • docker run --name nodejs-image-demo -p 80:8080 -d your_dockerhub_username/nodejs-image-demo

      Once your container is up and running, you can inspect a list of your running containers with docker ps:

      You will see the following output:

      Output

      CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e50ad27074a7 your_dockerhub_username/nodejs-image-demo "npm start" 8 seconds ago Up 7 seconds 0.0.0.0:80->8080/tcp nodejs-image-demo

      With your container running, you can now visit your application by navigating your browser to http://your_server_ip. You will see your application landing page once again:

      Application Landing Page

      Now that you have created an image for your application, you can push it to Docker Hub for future use.

      Step 4 — Using a Repository to Work with Images

      By pushing your application image to a registry like Docker Hub, you make it available for subsequent use as you build and scale your containers. We will demonstrate how this works by pushing the application image to a repository and then using the image to recreate our container.

      The first step to pushing the image is to log in to the Docker Hub account you created in the prerequisites:

      • docker login -u your_dockerhub_username -p your_dockerhub_password

      Logging in this way will create a ~/.docker/config.json file in your user's home directory with your Docker Hub credentials.

      You can now push the application image to Docker Hub using the tag you created earlier, your_dockerhub_username/nodejs-image-demo:

      • docker push your_dockerhub_username/nodejs-image-demo

      Let's test the utility of the image registry by destroying our current application container and image and rebuilding them with the image in our repository.

      First, list your running containers:

      You will see the following output:

      Output

      CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e50ad27074a7 your_dockerhub_username/nodejs-image-demo "npm start" 3 minutes ago Up 3 minutes 0.0.0.0:80->8080/tcp nodejs-image-demo

      Using the CONTAINER ID listed in your output, stop the running application container. Be sure to replace the highlighted ID below with your own CONTAINER ID:

      List your all of your images with the -a flag:

      You will see the following output with the name of your image, your_dockerhub_username/nodejs-image-demo, along with the node image and the other images from your build:

      Output

      REPOSITORY TAG IMAGE ID CREATED SIZE your_dockerhub_username/nodejs-image-demo latest 1c723fb2ef12 7 minutes ago 895MB <none> <none> e039d1b9a6a0 7 minutes ago 895MB <none> <none> dfa98908c5d1 7 minutes ago 895MB <none> <none> b9a714435a86 7 minutes ago 895MB <none> <none> 51de3ed7e944 7 minutes ago 895MB <none> <none> 5228d6c3b480 7 minutes ago 895MB <none> <none> 833b622e5492 8 minutes ago 893MB <none> <none> 5c47cc4725f1 8 minutes ago 893MB <none> <none> 5386324d89fb 8 minutes ago 893MB <none> <none> 631661025e2d 8 minutes ago 893MB node 10 f09e7c96b6de 17 hours ago 893MB

      Remove the stopped container and all of the images, including unused or dangling images, with the following command:

      Type y when prompted in the output to confirm that you would like to remove the stopped container and images. Be advised that this will also remove your build cache.

      You have now removed both the container running your application image and the image itself. For more information on removing Docker containers, images, and volumes, please see How To Remove Docker Images, Containers, and Volumes.

      With all of your images and containers deleted, you can now pull the application image from Docker Hub:

      • docker pull your_dockerhub_username/nodejs-image-demo

      List your images once again:

      You will see your application image:

      Output

      REPOSITORY TAG IMAGE ID CREATED SIZE your_dockerhub_username/nodejs-image-demo latest 1c723fb2ef12 11 minutes ago 895MB

      You can now rebuild your container using the command from Step 3:

      • docker run --name nodejs-image-demo -p 80:8080 -d your_dockerhub_username/nodejs-image-demo

      List your running containers:

      Output

      CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f6bc2f50dff6 your_dockerhub_username/nodejs-image-demo "npm start" 4 seconds ago Up 3 seconds 0.0.0.0:80->8080/tcp nodejs-image-demo

      Visit http://your_server_ip once again to view your running application.

      Conclusion

      In this tutorial you created a static web application with Express and Bootstrap, as well as a Docker image for this application. You used this image to create a container and pushed the image to Docker Hub. From there, you were able to destroy your image and container and recreate them using your Docker Hub repository.

      If you are interested in learning more about how to work with tools like Docker Compose and Docker Machine to create multi-container setups, you can look at the following guides:

      For general tips on working with container data, see:

      If you are interested in other Docker-related topics, please see our complete library of Docker tutorials.



      Source link

      How To Build a Modern Web Application to Manage Customer Information with Django and React on Ubuntu 18.04


      The author selected Open Sourcing Mental Illness Ltd to receive a donation as part of the Write for DOnations program.

      Introduction

      People use different types of devices to connect to the internet and browse the Web. Because of this, applications need to be accessible from a variety of locations. For traditional websites, having a responsive UI is usually enough, but more complex applications often require the use of other techniques and architectures. These include having separate REST back-end and front-end applications that can be implemented as client-side web applications, Progressive Web Apps (PWAs), or native mobile apps.

      Some tools that you can use when building more complex applications include:

      • React, a JavaScript framework that allows developers to build web and native frontends for their REST API backends.
      • Django, a free and open-source Python web framework that follows the model view controller (MVC) software architectural pattern.
      • Django REST framework, a powerful and flexible toolkit for building REST APIs in Django.

      In this tutorial, you will build a modern web application with a separate REST API backend and frontend using React, Django, and the Django REST Framework. By using React with Django, you’ll be able to benefit from the latest advancements in JavaScript and front-end development. Instead of building a Django application that uses a built-in template engine, you will use React as a UI library, taking advantage of its virtual Document Object Model (DOM), declarative approach, and components that quickly render changes in data.

      The web application you will build stores records about customers in a database, and you can use it as a starting point for a CRM application. When you are finished you’ll be able to create, read, update, and delete records using a React interface styled with Bootstrap 4.

      Prerequisites

      To complete this tutorial, you will need:

      Step 1 — Creating a Python Virtual Environment and Installing Dependencies

      In this step, we’ll create a virtual environment and install the required dependencies for our application, including Django, the Django REST framework, and django-cors-headers.

      Our application will use two different development servers for Django and React. They will run on different ports and will function as two separate domains. Because of this, we need to enable cross-origin resource sharing (CORS) to send HTTP requests from React to Django without being blocked by the browser.

      Navigate to your home directory and create a virtual environment using the venv Python 3 module:

      • cd ~
      • python3 -m venv ./env

      Activate the created virtual environment using source:

      Next, install the project's dependencies with pip. These will include:

      • Django: The web framework for the project.
      • Django REST framework: A third-party application that builds REST APIs with Django.
      • django-cors-headers: A package that enables CORS.

      Install the Django framework:

      • pip install django djangorestframework django-cors-headers

      With the project dependencies installed, you can create the Django project and the React frontend.

      Step 2 — Creating the Django Project

      In this step, we'll generate the Django project using the following commands and utilities:

      • django-admin startproject project-name: django-admin is a command-line utility used to accomplish tasks with Django. The startproject command creates a new Django project.

      • python manage.py startapp myapp: manage.py is a utility script, automatically added to each Django project, that performs a number of administrative tasks: creating new applications, migrating the database, and serving the Django project locally. Its startapp command creates a Django application inside the Django project. In Django, the term application describes a Python package that provides some set of features in a project.

      To begin, create the Django project with django-admin startproject. We will call our project djangoreactproject:

      • django-admin startproject djangoreactproject

      Before moving on, let's look at the directory structure of our Django project using the tree command.

      Tip: tree is a useful command for viewing file and directory structures from the command line. You can install it with the following command:

      • sudo apt-get install tree

      To use it, cd into the directory you want and type tree or provide the path to the starting point with tree /home/sammy/sammys-project.

      Navigate to the djangoreactproject folder within your project root and run the tree command:

      • cd ~/djangoreactproject
      • tree

      You will see the following output:

      Output

      ├── djangoreactproject │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── manage.py

      The ~/djangoreactproject folder is the root of the project. Within this folder, there are several files that will be important to your work:

      • manage.py: The utility script that does a number of administrative tasks.
      • settings.py: The main configuration file for the Django project where you can modify the project's settings. These settings include variables such as INSTALLED_APPS, a list of strings designating the enabled applications for your project. The Django documentation has more information about available settings.
      • urls.py: This file contains a list of URL patterns and related views. Each pattern maps a connection between a URL and the function that should be called for that URL. For more on URLs and views, please refer to our tutorial on How To Create Django Views.

      Our first step in working with the project will be to configure the packages we installed in the previous step, including the Django REST framework and the Django CORS package, by adding them to settings.py. Open the file with nano or your favorite editor:

      • nano ~/djangoreactproject/djangoreactproject/settings.py

      Navigate to the INSTALLED_APPS setting and add the rest_framework and corsheaders applications to the bottom of the list:

      ~/djangoreactproject/djangoreactproject/settings.py

      ...
      INSTALLED_APPS = [
          'django.contrib.admin',
          'django.contrib.auth',
          'django.contrib.contenttypes',
          'django.contrib.sessions',
          'django.contrib.messages',
          'django.contrib.staticfiles',
          'rest_framework',
          'corsheaders'
      ]
      

      Next, add the corsheaders.middleware.CorsMiddleware middleware from the previously installed CORS package to the MIDDLEWARE setting. This setting is a list of middlewares, a Python class that contains code processed each time your web application handles a request or response:

      ~/djangoreactproject/djangoreactproject/settings.py

      ...
      
      MIDDLEWARE = [
      ...
      'django.contrib.messages.middleware.MessageMiddleware',
      'django.middleware.clickjacking.XFrameOptionsMiddleware',
      'corsheaders.middleware.CorsMiddleware'
      ]
      

      Next, you can enable CORS. The CORS_ORIGIN_ALLOW_ALL setting specifies whether or not you want to allow CORS for all domains, and CORS_ORIGIN_WHITELIST is a Python tuple that contains allowed URLs. In our case, because the React development server will be running at http://localhost:3000, we will add new CORS_ORIGIN_ALLOW_ALL = False and CORS_ORIGIN_WHITELIST('localhost:3000',) settings to our settings.py file. Add these settings anywhere in the file:

      ~/djangoreactproject/djangoreactproject/settings.py

      
      ...
      CORS_ORIGIN_ALLOW_ALL = False
      
      CORS_ORIGIN_WHITELIST = (
             'localhost:3000',
      )
      ...
      

      You can find more configuration options in the django-cors-headers docs.

      Save the file and exit the editor when you are finished.

      Still in the ~/djangoreactproject directory, make a new Django application called customers:

      • python manage.py startapp customers

      This will contain the models and views for managing customers. Models define the fields and behaviors of our application data, while views enable our application to properly handle web requests and return the required responses.

      Next, add this application to the list of installed applications in your project's settings.py file so Django will recognize it as part of the project. Open settings.py again:

      • nano ~/djangoreactproject/djangoreactproject/settings.py

      Add the customers application:

      ~/djangoreactproject/djangoreactproject/settings.py

      ...
      INSTALLED_APPS = [
          ...
          'rest_framework',
          'corsheaders',
          'customers'
      ]
      ...
      

      Next, migrate the database and start the local development server. Migrations are Django’s way of propagating the changes you make to your models into your database schema. These changes can include things like adding a field or deleting a model, for example. For more on models and migrations, see How To Create Django Models.

      Migrate the database:

      Start the local development server:

      • python manage.py runserver

      You will see output similar to the following:

      Output

      Performing system checks... System check identified no issues (0 silenced). October 22, 2018 - 15:14:50 Django version 2.1.2, using settings 'djangoreactproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.

      Your web application will be running from http://127.0.0.1:8000. If you navigate to this address in your web browser you should see the following page:

      Django demo page

      At this point, leave the application running and open a new terminal to continue developing the project.

      Step 3 — Creating the React Frontend

      In this section, we're going to create the front-end application of our project using React.

      React has an official utility that allows you to quickly generate React projects without having to configure Webpack directly. Webpack is a module bundler used to bundle web assets such as JavaScript code, CSS, and images. Typically, before you can use Webpack you need to set various configuration options, but thanks to the create-react-app utility you don't have to deal with Webpack directly until you decide you need more control. To run create-react-app you can use npx, a tool that executes npm package binaries.

      In your second terminal, make sure you are in your project directory:

      Create a React project called frontend using create-react-app and npx:

      • npx create-react-app frontend

      Next, navigate inside your React application and start the development server:

      • cd ~/djangoreactproject/frontend
      • npm start

      You application will be running from http://localhost:3000/:

      React demo page

      Leave the React development server running and open another terminal window to proceed.

      To see the directory structure of the entire project at this point, navigate to the root folder and run tree again:

      • cd ~/djangoreactproject
      • tree

      You'll see a structure like this:

      Output

      ├── customers │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── djangoreactproject │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── frontend │ ├── package.json │ ├── public │ │ ├── favicon.ico │ │ ├── index.html │ │ └── manifest.json │ ├── README.md │ ├── src │ │ ├── App.css │ │ ├── App.js │ │ ├── App.test.js │ │ ├── index.css │ │ ├── index.js │ │ ├── logo.svg │ │ └── registerServiceWorker.js │ └── yarn.lock └── manage.py

      Our application will use Bootstrap 4 to style the React interface, so we will include it in the frontend/src/App.css file, which manages our CSS settings. Open the file:

      • nano ~/djangoreactproject/frontend/src/App.css

      Add the following import to the beginning of the file. You can delete the file's existing content, though that's not required:

      ~/djangoreactproject/frontend/src/App.css

      @import  'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css';
      

      Here, @import is a CSS instruction that's used to import style rules from other style sheets.

      Now that we have created both the back-end and front-end applications, let's create the Customer model and some demo data.

      Step 4 — Creating the Customer Model and Initial Data

      After creating the Django application and the React frontend, our next step will be to create the Customer model, which represents the database table that will hold information about customers. You don't need any SQL since the Django Object Relational Mapper (ORM) will handle database operations by mapping Python classes and variables to SQL tables and columns. In this way the Django ORM abstracts SQL interactions with the database through a Python interface.

      Activate your virtual environment again:

      • cd ~
      • source env/bin/activate

      Move to the customers directory, and open models.py, a Python file that holds the models of your application:

      • cd ~/djangoreactproject/customers/
      • nano models.py

      The file will contain the following content:

      ~/djangoreactproject/customers/models.py

      from django.db import models
      # Create your models here.
      

      The Customer model's API is already imported in the file thanks to the from django.db import models import statement. You will now add the Customer class, which extends models.Model. Each model in Django is a Python class that extends django.db.models.Model.

      The Customer model will have these database fields:

      • first_name — The first name of the customer.
      • last_name — The last name of the customer.
      • email — The email address of the customer.
      • phone — The phone number of the customer.
      • address — The address of the customer.
      • description — The description of the customer.
      • createdAt — The date when the customer is added.

      We will also add the __str__() function, which defines how the model will be displayed. In our case, it will be with the customer's first name. For more on constructing classes and defining objects, please see How To Construct Classes and Define Objects in Python 3.

      Add the following code to the file:

      ~/djangoreactproject/customers/models.py

      from django.db import models
      
      class Customer(models.Model):
          first_name = models.CharField("First name", max_length=255)
          last_name = models.CharField("Last name", max_length=255)
          email = models.EmailField()
          phone = models.CharField(max_length=20)
          address =  models.TextField(blank=True, null=True)
          description = models.TextField(blank=True, null=True)
          createdAt = models.DateTimeField("Created At", auto_now_add=True)
      
          def __str__(self):
              return self.first_name
      

      Next, migrate the database to create the database tables. The makemigrations command creates the migration files where model changes will be added, and migrate applies the changes in the migrations files to the database.

      Navigate back to the project's root folder:

      Run the following to create the migration files:

      • python manage.py makemigrations

      You will get output that looks like this:

      Output

      customers/migrations/0001_initial.py - Create model Customer

      Apply these changes to the database:

      You will see output indicating a successful migration:

      Output

      Operations to perform: Apply all migrations: admin, auth, contenttypes, customers, sessions Running migrations: Applying customers.0001_initial... OK

      Next, you will use a data migration file to create initial customer data. A data migration file is a migration that adds or alters data in the database. Create an empty data migration file for the customers application:

      • python manage.py makemigrations --empty --name customers customers

      You will see the following confirmation with the name of your migration file:

      Output

      Migrations for 'customers': customers/migrations/0002_customers.py

      Note that the name of your migration file is 0002_customers.py.

      Next, navigate inside the migrations folder of the customers application:

      • cd ~/djangoreactproject/customers/migrations

      Open the created migration file:

      This is the initial content of the file:

      ~/djangoreactproject/customers/migrations/0002_customers.py

      from django.db import migrations
      
      class Migration(migrations.Migration):
          dependencies = [
              ('customers', '0001_initial'),
          ]
          operations = [
          ]        
      

      The import statement imports the migrations API, a Django API for creating migrations, from django.db, a built-in package that contains classes for working with databases.

      The Migration class is a Python class that describes the operations that are executed when migrating databases. This class extends migrations.Migration and has two lists:

      • dependencies: Contains the dependent migrations.
      • operations: Contains the operations that will be executed when we apply the migration.

      Next, add a method to create demo customer data. Add the following method before the definition of the Migration class:

      ~/djangoreactproject/customers/migrations/0002_customers.py

      ...
      def create_data(apps, schema_editor):
          Customer = apps.get_model('customers', 'Customer')
          Customer(first_name="Customer 001", last_name="Customer 001", email="customer001@email.com", phone="00000000", address="Customer 000 Address", description= "Customer 001 description").save()
      
      ...
      

      In this method, we are grabbing the Customer class of our customers app and creating a demo customer to insert into the database.

      To get the Customer class, which will enable the creation of new customers, we use the get_model() method of the apps object. The apps object represents the registry of installed applications and their database models.

      The apps object will be passed from the RunPython() method when we use it to run create_data(). Add the migrations.RunPython() method to the empty operations list:

      ~/djangoreactproject/customers/migrations/0002_customers.py

      
      ...
          operations = [
              migrations.RunPython(create_data),
          ]  
      

      RunPython() is part of the Migrations API that allows you to run custom Python code in a migration. Our operations list specifies that this method will be executed when we apply the migration.

      This is the complete file:

      ~/djangoreactproject/customers/migrations/0002_customers.py

      from django.db import migrations
      
      def create_data(apps, schema_editor):
          Customer = apps.get_model('customers', 'Customer')
          Customer(first_name="Customer 001", last_name="Customer 001", email="customer001@email.com", phone="00000000", address="Customer 000 Address", description= "Customer 001 description").save()
      
      class Migration(migrations.Migration):
          dependencies = [
              ('customers', '0001_initial'),
          ]
          operations = [
              migrations.RunPython(create_data),
          ]        
      

      For more information on data migrations, see the documentation on data migrations in Django

      To migrate your database, first navigate back to the root folder of your project:

      Migrate your database to create the demo data:

      You will see output that confirms the migration:

      Output

      Operations to perform: Apply all migrations: admin, auth, contenttypes, customers, sessions Running migrations: Applying customers.0002_customers... OK

      For more details on this process, refer back to How To Create Django Models.

      With the Customer model and demo data created, we can move on to building the REST API.

      Step 5 — Creating the REST API

      In this step we'll create the REST API using the Django REST Framework. We'll create several different API views. An API view is a function that handles an API request or call, while an API endpoint is a unique URL that represents a touchpoint with the REST system. For example, when the user sends a GET request to an API endpoint, Django calls the corresponding function or API view to handle the request and return any possible results.

      We'll also make use of serializers. A serializer in the Django REST Framework allows complex model instances and QuerySets to be converted into JSON format for API consumption. The serializer class can also work in the other direction, providing mechanisms for parsing and deserializing data into Django models and QuerySets.

      Our API endpoints will include:

      • api/customers: This endpoint is used to create customers and returns paginated sets of customers.
      • api/customers/<pk>: This endpoint is used to get, update, and delete single customers by primary key or id.

      We'll also create URLs in the project's urls.py file for the corresponding endpoints (i.e api/customers and api/customers/<pk>).

      Let's start by creating the serializer class for our Customer model.

      Adding the Serializer Class

      Creating a serializer class for our Customer model is necessary for transforming customer instances and QuerySets to and from JSON. To create the serializer class, first make a serializers.py file inside the customers application:

      • cd ~/djangoreactproject/customers/
      • nano serializers.py

      Add the following code to import the serializers API and Customer model:

      ~/djangoreactproject/customers/serializers.py

      from rest_framework import serializers
      from .models import Customer
      

      Next, create a serializer class that extends serializers.ModelSerializer and specifies the fields that will be serialized:

      ~/djangoreactproject/customers/serializers.py

      
      ...
      class CustomerSerializer(serializers.ModelSerializer):
      
          class Meta:
              model = Customer 
              fields = ('pk','first_name', 'last_name', 'email', 'phone','address','description')
      

      The Meta class specifies the model and fields to serialize: pk,first_name, last_name, email, phone, address,description.

      This is the full content of the file:

      ~/djangoreactproject/customers/serializers.py

      from rest_framework import serializers
      from .models import Customer
      
      class CustomerSerializer(serializers.ModelSerializer):
      
          class Meta:
              model = Customer 
              fields = ('pk','first_name', 'last_name', 'email', 'phone','address','description')
      

      Now that we've created our serializer class, we can add the API views.

      Adding the API Views

      In this section, we'll create the API views for our application that will be called by Django when the user visits the endpoint corresponding to the view function.

      Open ~/djangoreactproject/customers/views.py:

      • nano ~/djangoreactproject/customers/views.py

      Delete what's there and add the following imports:

      ~/djangoreactproject/customers/views.py

      from rest_framework.response import Response
      from rest_framework.decorators import api_view
      from rest_framework import status
      
      from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
      from .models import Customer 
      from .serializers import *
      

      We are importing the serializer we created, along with the Customer model and the Django and Django REST Framework APIs.

      Next, add the view for processing POST and GET HTTP requests:

      ~/djangoreactproject/customers/views.py

      ...
      
      @api_view(['GET', 'POST'])
      def customers_list(request):
          """
       List  customers, or create a new customer.
       """
          if request.method == 'GET':
              data = []
              nextPage = 1
              previousPage = 1
              customers = Customer.objects.all()
              page = request.GET.get('page', 1)
              paginator = Paginator(customers, 10)
              try:
                  data = paginator.page(page)
              except PageNotAnInteger:
                  data = paginator.page(1)
              except EmptyPage:
                  data = paginator.page(paginator.num_pages)
      
              serializer = CustomerSerializer(data,context={'request': request} ,many=True)
              if data.has_next():
                  nextPage = data.next_page_number()
              if data.has_previous():
                  previousPage = data.previous_page_number()
      
              return Response({'data': serializer.data , 'count': paginator.count, 'numpages' : paginator.num_pages, 'nextlink': '/api/customers/?page=' + str(nextPage), 'prevlink': '/api/customers/?page=' + str(previousPage)})
      
          elif request.method == 'POST':
              serializer = CustomerSerializer(data=request.data)
              if serializer.is_valid():
                  serializer.save()
                  return Response(serializer.data, status=status.HTTP_201_CREATED)
              return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
      

      First we use the @api_view(['GET', 'POST']) decorator to create an API view that can accept GET and POST requests. A decorator is a function that takes another function and dynamically extends it.

      In the method body we use the request.method variable to check the current HTTP method and execute the corresponding logic depending on the request type:

      • If it's a GET request, the method paginates the data using Django Paginator, and returns the first page of data after serialization, the count of available customers, the number of available pages, and the links to the previous and next pages. Paginator is a built-in Django class that paginates a list of data into pages and provides methods to access the items for each page.
      • If it's a POST request, the method serializes the received customer data and then calls the save() method of the serializer object. It then returns a Response object, an instance of HttpResponse, with a 201 status code. Each view you create is responsible for returing an HttpResponse object. The save() method saves the serialized data in the database.

      For more about HttpResponse and views, see this discussion of creating view functions.

      Now add the API view that will be responsible for processing the GET, PUT, and DELETE requests for getting, updating, and deleting customers by pk (primary key):

      ~/djangoreactproject/customers/views.py

      
      ...
      @api_view(['GET', 'PUT', 'DELETE'])
      def customers_detail(request, pk):
       """
       Retrieve, update or delete a customer by id/pk.
       """
          try:
              customer = Customer.objects.get(pk=pk)
          except Customer.DoesNotExist:
              return Response(status=status.HTTP_404_NOT_FOUND)
      
          if request.method == 'GET':
              serializer = CustomerSerializer(customer,context={'request': request})
              return Response(serializer.data)
      
          elif request.method == 'PUT':
              serializer = CustomerSerializer(customer, data=request.data,context={'request': request})
              if serializer.is_valid():
                  serializer.save()
                  return Response(serializer.data)
              return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
      
          elif request.method == 'DELETE':
              customer.delete()
              return Response(status=status.HTTP_204_NO_CONTENT)
      

      The method is decorated with @api_view(['GET', 'PUT', 'DELETE']) to denote that it's an API view that can accept GET, PUT, and DELETE requests.

      The check in the request.method field verifies the request method, and depending on its value calls the right logic:

      • If it's a GET request, customer data is serialized and sent using a Response object.
      • If it's a PUT request, the method creates a serializer for new customer data. Next, it calls the save() method of the created serializer object. Finally, it sends a Response object with the updated customer.
      • If it's a DELETE request, the method calls the delete() method of the customer object to delete it, then returns a Response object with no data.

      The completed file looks like this:

      ~/djangoreactproject/customers/views.py

      from rest_framework.response import Response
      from rest_framework.decorators import api_view
      from rest_framework import status
      
      from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
      from .models import Customer 
      from .serializers import *
      
      
      @api_view(['GET', 'POST'])
      def customers_list(request):
          """
       List  customers, or create a new customer.
       """
          if request.method == 'GET':
              data = []
              nextPage = 1
              previousPage = 1
              customers = Customer.objects.all()
              page = request.GET.get('page', 1)
              paginator = Paginator(customers, 5)
              try:
                  data = paginator.page(page)
              except PageNotAnInteger:
                  data = paginator.page(1)
              except EmptyPage:
                  data = paginator.page(paginator.num_pages)
      
              serializer = CustomerSerializer(data,context={'request': request} ,many=True)
              if data.has_next():
                  nextPage = data.next_page_number()
              if data.has_previous():
                  previousPage = data.previous_page_number()
      
              return Response({'data': serializer.data , 'count': paginator.count, 'numpages' : paginator.num_pages, 'nextlink': '/api/customers/?page=' + str(nextPage), 'prevlink': '/api/customers/?page=' + str(previousPage)})
      
          elif request.method == 'POST':
              serializer = CustomerSerializer(data=request.data)
              if serializer.is_valid():
                  serializer.save()
                  return Response(serializer.data, status=status.HTTP_201_CREATED)
              return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
      
      @api_view(['GET', 'PUT', 'DELETE'])
      def customers_detail(request, pk):
          """
       Retrieve, update or delete a customer by id/pk.
       """
          try:
              customer = Customer.objects.get(pk=pk)
          except Customer.DoesNotExist:
              return Response(status=status.HTTP_404_NOT_FOUND)
      
          if request.method == 'GET':
              serializer = CustomerSerializer(customer,context={'request': request})
              return Response(serializer.data)
      
          elif request.method == 'PUT':
              serializer = CustomerSerializer(customer, data=request.data,context={'request': request})
              if serializer.is_valid():
                  serializer.save()
                  return Response(serializer.data)
              return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
      
          elif request.method == 'DELETE':
              customer.delete()
              return Response(status=status.HTTP_204_NO_CONTENT)
      

      We can now move on to creating our endpoints.

      Adding API Endpoints

      We will now create the API endpoints: api/customers/, for querying and creating customers, and api/customers/<pk>, for getting, updating, or deleting single customers by their pk.

      Open ~/djangoreactproject/djangoreactproject/urls.py:

      • nano ~/djangoreactproject/djangoreactproject/urls.py

      Leave what's there, but add the import to the customers views at the top of the file:

      ~/djangoreactproject/djangoreactproject/urls.py

      from django.contrib import admin
      from django.urls import path
      from customers import views
      from django.conf.urls import url
      

      Next, add the api/customers/ and api/customers/<pk> URLs to the urlpatterns list that contains the application's URLs:

      ~/djangoreactproject/djangoreactproject/urls.py

      ...
      
      urlpatterns = [
          path('admin/', admin.site.urls),
          url(r'^api/customers/$', views.customers_list),
          url(r'^api/customers/(?P<pk>[0-9]+)$', views.customers_detail),
      ]
      

      With our REST endpoints created, let's see how we can consume them.

      Step 6 — Consuming the REST API with Axios

      In this step, we'll install Axios, the HTTP client we'll use to make API calls. We'll also create a class to consume the API endpoints we've created.

      First, deactivate your virtual environment:

      Next, navigate to your frontend folder:

      • cd ~/djangoreactproject/frontend

      Install axios from npm using:

      The --save option adds the axios dependency to your application's package.json file.

      Next, create a JavaScript file called CustomersService.js, which will contain the code to call the REST APIs. We'll make this inside the src folder, where the application code for our project will live:

      • cd src
      • nano CustomersService.js

      Add the following code, which contains methods to connect to the Django REST API:

      ~/djangoreactproject/frontend/src/CustomersService.js

      import axios from 'axios';
      const API_URL = 'http://localhost:8000';
      
      export default class CustomersService{
      
          constructor(){}
      
      
          getCustomers() {
              const url = `${API_URL}/api/customers/`;
              return axios.get(url).then(response => response.data);
          }  
          getCustomersByURL(link){
              const url = `${API_URL}${link}`;
              return axios.get(url).then(response => response.data);
          }
          getCustomer(pk) {
              const url = `${API_URL}/api/customers/${pk}`;
              return axios.get(url).then(response => response.data);
          }
          deleteCustomer(customer){
              const url = `${API_URL}/api/customers/${customer.pk}`;
              return axios.delete(url);
          }
          createCustomer(customer){
              const url = `${API_URL}/api/customers/`;
              return axios.post(url,customer);
          }
          updateCustomer(customer){
              const url = `${API_URL}/api/customers/${customer.pk}`;
              return axios.put(url,customer);
          }
      }
      

      The CustomersService class will call the following Axios methods:

      • getCustomers(): Gets first page of customers.
      • getCustomersByURL(): Gets customers by URL. This makes it possible to get the next pages of customers by passing links such as /api/customers/?page=2.
      • getCustomer(): Gets a customer by primary key.
      • createCustomer(): Creates a customer.
      • updateCustomer(): Updates a customer.
      • deleteCustomer(): Deletes a customer.

      We can now display the data from our API in our React UI interface by creating a CustomersList component.

      Step 7 — Displaying Data from the API in the React Application

      In this step, we'll create the CustomersList React component. A React component represents a part of the UI; it also lets you split the UI into independent, reusable pieces.

      Begin by creating CustomersList.js in frontend/src:

      • nano ~/djangoreactproject/frontend/src/CustomersList.js

      Start by importing React and Component to create a React component:

      ~/djangoreactproject/frontend/src/CustomersList.js

      import  React, { Component } from  'react';
      

      Next, import and instantiate the CustomersService module you created in the previous step, which provides methods that interface with the REST API backend:

      ~/djangoreactproject/frontend/src/CustomersList.js

      
      ...
      import  CustomersService  from  './CustomersService';
      
      const  customersService  =  new  CustomersService();
      

      Next, create a CustomersList component that extends Component to call the REST API. A React component should extend or subclass the Component class. For more about E6 classes and inheritence, please see our tutorial on Understanding Classes in JavaScript.

      Add the following code to create a React component that extends react.Component:

      ~/djangoreactproject/frontend/src/CustomersList.js

      
      ...
      class  CustomersList  extends  Component {
      
          constructor(props) {
              super(props);
              this.state  = {
                  customers: [],
                  nextPageURL:  ''
              };
              this.nextPage  =  this.nextPage.bind(this);
              this.handleDelete  =  this.handleDelete.bind(this);
          }
      }
      export  default  CustomersList;
      

      Inside the constructor, we are initializing the state object. This holds the state variables of our component using an empty customers array. This array will hold customers and a nextPageURL that will hold the URL of the next page to retrieve from the back-end API. We are also binding the nextPage() and handleDelete() methods to this so they will be accessible from the HTML code.

      Next, add the componentDidMount() method and a call to getCustomers() within the CustomersList class, before the closing curly brace.

      The componentDidMount() method is a lifecycle method of the component that is called when the component is created and inserted into the DOM. getCustomers() calls the Customers Service object to get the first page of data and the link of the next page from the Django backend:

      ~/djangoreactproject/frontend/src/CustomersList.js

      
      ...
      componentDidMount() {
          var  self  =  this;
          customersService.getCustomers().then(function (result) {
              self.setState({ customers:  result.data, nextPageURL:  result.nextlink})
          });
      }
      

      Now add the handleDelete() method, which handles deleting a customer, below componentDidMount():

      ~/djangoreactproject/frontend/src/CustomersList.js

      
      ...
      handleDelete(e,pk){
          var  self  =  this;
          customersService.deleteCustomer({pk :  pk}).then(()=>{
              var  newArr  =  self.state.customers.filter(function(obj) {
                  return  obj.pk  !==  pk;
              });
              self.setState({customers:  newArr})
          });
      }
      

      The handleDelete() method calls the deleteCustomer() method to delete a customer using its pk (primary key). If the operation is successful, the customers array is filtered out for the removed customer.

      Next, add a nextPage() method to get the data for the next page and update the next page link:

      ~/djangoreactproject/frontend/src/CustomersList.js

      
      ...
      nextPage(){
          var  self  =  this;
          customersService.getCustomersByURL(this.state.nextPageURL).then((result) => {
              self.setState({ customers:  result.data, nextPageURL:  result.nextlink})
          });
      }
      

      The nextPage() method calls a getCustomersByURL() method, which takes the next page URL from the state object, this.state.nextPageURL, and updates the customers array with the returned data.

      Finally, add the component render() method, which renders a table of customers from the component state:

      ~/djangoreactproject/frontend/src/CustomersList.js

      
      ...
      render() {
      
          return (
          <div  className="customers--list">
              <table  className="table">
                  <thead  key="thead">
                  <tr>
                      <th>#</th>
                      <th>First Name</th>
                      <th>Last Name</th>
                      <th>Phone</th>
                      <th>Email</th>
                      <th>Address</th>
                      <th>Description</th>
                      <th>Actions</th>
                  </tr>
                  </thead>
                  <tbody>
                      {this.state.customers.map( c  =>
                      <tr  key={c.pk}>
                          <td>{c.pk}  </td>
                          <td>{c.first_name}</td>
                          <td>{c.last_name}</td>
                          <td>{c.phone}</td>
                          <td>{c.email}</td>
                          <td>{c.address}</td>
                          <td>{c.description}</td>
                          <td>
                          <button  onClick={(e)=>  this.handleDelete(e,c.pk) }> Delete</button>
                          <a  href={"/customer/" + c.pk}> Update</a>
                          </td>
                      </tr>)}
                  </tbody>
              </table>
              <button  className="btn btn-primary"  onClick=  {  this.nextPage  }>Next</button>
          </div>
          );
      }
      

      This is the full content of the file:

      ~/djangoreactproject/frontend/src/CustomersList.js

      import  React, { Component } from  'react';
      import  CustomersService  from  './CustomersService';
      
      const  customersService  =  new  CustomersService();
      
      class  CustomersList  extends  Component {
      
      constructor(props) {
          super(props);
          this.state  = {
              customers: [],
              nextPageURL:  ''
          };
          this.nextPage  =  this.nextPage.bind(this);
          this.handleDelete  =  this.handleDelete.bind(this);
      }
      
      componentDidMount() {
          var  self  =  this;
          customersService.getCustomers().then(function (result) {
              console.log(result);
              self.setState({ customers:  result.data, nextPageURL:  result.nextlink})
          });
      }
      handleDelete(e,pk){
          var  self  =  this;
          customersService.deleteCustomer({pk :  pk}).then(()=>{
              var  newArr  =  self.state.customers.filter(function(obj) {
                  return  obj.pk  !==  pk;
              });
      
              self.setState({customers:  newArr})
          });
      }
      
      nextPage(){
          var  self  =  this;
          console.log(this.state.nextPageURL);        
          customersService.getCustomersByURL(this.state.nextPageURL).then((result) => {
              self.setState({ customers:  result.data, nextPageURL:  result.nextlink})
          });
      }
      render() {
      
          return (
              <div  className="customers--list">
                  <table  className="table">
                  <thead  key="thead">
                  <tr>
                      <th>#</th>
                      <th>First Name</th>
                      <th>Last Name</th>
                      <th>Phone</th>
                      <th>Email</th>
                      <th>Address</th>
                      <th>Description</th>
                      <th>Actions</th>
                  </tr>
                  </thead>
                  <tbody>
                  {this.state.customers.map( c  =>
                      <tr  key={c.pk}>
                      <td>{c.pk}  </td>
                      <td>{c.first_name}</td>
                      <td>{c.last_name}</td>
                      <td>{c.phone}</td>
                      <td>{c.email}</td>
                      <td>{c.address}</td>
                      <td>{c.description}</td>
                      <td>
                      <button  onClick={(e)=>  this.handleDelete(e,c.pk) }> Delete</button>
                      <a  href={"/customer/" + c.pk}> Update</a>
                      </td>
                  </tr>)}
                  </tbody>
                  </table>
                  <button  className="btn btn-primary"  onClick=  {  this.nextPage  }>Next</button>
              </div>
              );
        }
      }
      export  default  CustomersList;
      

      Now that we've created the CustomersList component for displaying the list of customers, we can add the component that handles customer creation and updates.

      Step 8 — Adding the Customer Create and Update React Component

      In this step, we'll create the CustomerCreateUpdate component, which will handle creating and updating customers. It will do this by providing a form that users can use to either enter data about a new customer or update an existing entry.

      In frontend/src, create a CustomerCreateUpdate.js file:

      • nano ~/djangoreactproject/frontend/src/CustomerCreateUpdate.js

      Add the following code to create a React component, importing React and Component:

      ~/djangoreactproject/frontend/src/CustomerCreateUpdate.js

      import  React, { Component } from  'react';
      

      We can also import and instantiate the CustomersService class we created in the previous step, which provides methods that interface with the REST API backend:

      ~/djangoreactproject/frontend/src/CustomerCreateUpdate.js

      ...
      import  CustomersService  from  './CustomersService';
      
      const  customersService  =  new  CustomersService();
      

      Next, create a CustomerCreateUpdate component that extends Component to create and update customers:

      ~/djangoreactproject/frontend/src/CustomerCreateUpdate.js

      
      ...
      class  CustomerCreateUpdate  extends  Component {
      
          constructor(props) {
              super(props);
          }
      
      }
      export default CustomerCreateUpdate;
      

      Within the class definition, add the render() method of the component, which renders an HTML form that takes information about the customer:

      ~/djangoreactproject/frontend/src/CustomerCreateUpdate.js

      
      ...
      render() {
              return (
                <form onSubmit={this.handleSubmit}>
                <div className="form-group">
                  <label>
                    First Name:</label>
                    <input className="form-control" type="text" ref='firstName' />
      
                  <label>
                    Last Name:</label>
                    <input className="form-control" type="text" ref='lastName'/>
      
                  <label>
                    Phone:</label>
                    <input className="form-control" type="text" ref='phone' />
      
                  <label>
                    Email:</label>
                    <input className="form-control" type="text" ref='email' />
      
                  <label>
                    Address:</label>
                    <input className="form-control" type="text" ref='address' />
      
                  <label>
                    Description:</label>
                    <textarea className="form-control" ref='description' ></textarea>
      
      
                  <input className="btn btn-primary" type="submit" value="Submit" />
                  </div>
                </form>
              );
        }
      

      For each form input element, the method adds a ref property to access and set the value of the form element.

      Next, above the render() method, define a handleSubmit(event) method so that you have the proper functionality when a user clicks on the submit button:

      ~/djangoreactproject/frontend/src/CustomerCreateUpdate.js

      
      ...
      handleSubmit(event) {
          const { match: { params } } =  this.props;
          if(params  &&  params.pk){
              this.handleUpdate(params.pk);
          }
          else
          {
              this.handleCreate();
          }
          event.preventDefault();
      }
      
      ...
      

      The handleSubmit(event) method handles the form submission and, depending on the route, calls either the handleUpdate(pk) method to update the customer with the passed pk, or the handleCreate() method to create a new customer. We will define these methods shortly.

      Back on the component constructor, bind the newly added handleSubmit() method to this so you can access it in your form:

      ~/djangoreactproject/frontend/src/CustomerCreateUpdate.js

      ...
      class CustomerCreateUpdate extends Component {
      
      constructor(props) {
          super(props);
          this.handleSubmit = this.handleSubmit.bind(this);
      }
      ...
      

      Next, define the handleCreate() method to create a customer from the form data. Above the handleSubmit(event) method, add the following code:

      ~/djangoreactproject/frontend/src/CustomerCreateUpdate.js

      
      ...
      handleCreate(){
          customersService.createCustomer(
              {
              "first_name":  this.refs.firstName.value,
              "last_name":  this.refs.lastName.value,
              "email":  this.refs.email.value,
              "phone":  this.refs.phone.value,
              "address":  this.refs.address.value,
              "description":  this.refs.description.value
              }).then((result)=>{
                      alert("Customer created!");
              }).catch(()=>{
                      alert('There was an error! Please re-check your form.');
              });
      }
      
      ...
      

      The handleCreate() method will be used to create a customer from inputted data. It calls the corresponding CustomersService.createCustomer() method that makes the actual API call to the backend to create a customer.

      Next, below the handleCreate() method, define the handleUpdate(pk) method to implement updates:

      ~/djangoreactproject/frontend/src/CustomerCreateUpdate.js

      
      ...
      handleUpdate(pk){
      customersService.updateCustomer(
          {
          "pk":  pk,
          "first_name":  this.refs.firstName.value,
          "last_name":  this.refs.lastName.value,
          "email":  this.refs.email.value,
          "phone":  this.refs.phone.value,
          "address":  this.refs.address.value,
          "description":  this.refs.description.value
          }
          ).then((result)=>{
      
              alert("Customer updated!");
          }).catch(()=>{
              alert('There was an error! Please re-check your form.');
          });
      }
      

      The updateCustomer() method will update a customer by pk using the new information from the customer information form. It calls the customersService.updateCustomer() method.

      Next, add a componentDidMount() method. If the the user visits a customer/:pk route, we want to fill the form with information related to the customer using the primary key from the URL. To do that, we can add the getCustomer(pk) method after the component gets mounted in the lifecycle event of componentDidMount(). Add the following code below the component constructor to add this method:

      ~/djangoreactproject/frontend/src/CustomerCreateUpdate.js

      
      ...
      componentDidMount(){
          const { match: { params } } =  this.props;
          if(params  &&  params.pk)
          {
              customersService.getCustomer(params.pk).then((c)=>{
                  this.refs.firstName.value  =  c.first_name;
                  this.refs.lastName.value  =  c.last_name;
                  this.refs.email.value  =  c.email;
                  this.refs.phone.value  =  c.phone;
                  this.refs.address.value  =  c.address;
                  this.refs.description.value  =  c.description;
              })
          }
      }
      

      This is the full content of the file:

      ~/djangoreactproject/frontend/src/CustomerCreateUpdate.js

      import React, { Component } from 'react';
      import CustomersService from './CustomersService';
      
      const customersService = new CustomersService();
      
      class CustomerCreateUpdate extends Component {
          constructor(props) {
              super(props);
      
              this.handleSubmit = this.handleSubmit.bind(this);
            }
      
            componentDidMount(){
              const { match: { params } } = this.props;
              if(params && params.pk)
              {
                customersService.getCustomer(params.pk).then((c)=>{
                  this.refs.firstName.value = c.first_name;
                  this.refs.lastName.value = c.last_name;
                  this.refs.email.value = c.email;
                  this.refs.phone.value = c.phone;
                  this.refs.address.value = c.address;
                  this.refs.description.value = c.description;
                })
              }
            }
      
            handleCreate(){
              customersService.createCustomer(
                {
                  "first_name": this.refs.firstName.value,
                  "last_name": this.refs.lastName.value,
                  "email": this.refs.email.value,
                  "phone": this.refs.phone.value,
                  "address": this.refs.address.value,
                  "description": this.refs.description.value
              }          
              ).then((result)=>{
                alert("Customer created!");
              }).catch(()=>{
                alert('There was an error! Please re-check your form.');
              });
            }
            handleUpdate(pk){
              customersService.updateCustomer(
                {
                  "pk": pk,
                  "first_name": this.refs.firstName.value,
                  "last_name": this.refs.lastName.value,
                  "email": this.refs.email.value,
                  "phone": this.refs.phone.value,
                  "address": this.refs.address.value,
                  "description": this.refs.description.value
              }          
              ).then((result)=>{
                console.log(result);
                alert("Customer updated!");
              }).catch(()=>{
                alert('There was an error! Please re-check your form.');
              });
            }
            handleSubmit(event) {
              const { match: { params } } = this.props;
      
              if(params && params.pk){
                this.handleUpdate(params.pk);
              }
              else
              {
                this.handleCreate();
              }
      
              event.preventDefault();
            }
      
            render() {
              return (
                <form onSubmit={this.handleSubmit}>
                <div className="form-group">
                  <label>
                    First Name:</label>
                    <input className="form-control" type="text" ref='firstName' />
      
                  <label>
                    Last Name:</label>
                    <input className="form-control" type="text" ref='lastName'/>
      
                  <label>
                    Phone:</label>
                    <input className="form-control" type="text" ref='phone' />
      
                  <label>
                    Email:</label>
                    <input className="form-control" type="text" ref='email' />
      
                  <label>
                    Address:</label>
                    <input className="form-control" type="text" ref='address' />
      
                  <label>
                    Description:</label>
                    <textarea className="form-control" ref='description' ></textarea>
      
      
                  <input className="btn btn-primary" type="submit" value="Submit" />
                  </div>
                </form>
              );
            }  
      }
      
      export default CustomerCreateUpdate;
      

      With the CustomerCreateUpdate component created, we can update the main App component to add links to the different components we've created.

      Step 9 — Updating the Main App Component

      In this section, we'll update the App component of our application to create links to the components we've created in the previous steps.

      From the frontend folder, run the following command to install the React Router, which allows you to add routing and navigation between various React components:

      • cd ~/djangoreactproject/frontend
      • npm install --save react-router-dom

      Next, open ~/djangoreactproject/frontend/src/App.js:

      • nano ~/djangoreactproject/frontend/src/App.js

      Delete everything that's there and add the following code to import the necessary classes for adding routing. These include BrowserRouter, which creates a Router component, and Route, which creates a route component:

      ~/djangoreactproject/frontend/src/App.js

      import  React, { Component } from  'react';
      import { BrowserRouter } from  'react-router-dom'
      import { Route, Link } from  'react-router-dom'
      import  CustomersList  from  './CustomersList'
      import  CustomerCreateUpdate  from  './CustomerCreateUpdate'
      import  './App.css';
      

      BrowserRouter keeps the UI in sync with the URL using the HTML5 history API.

      Next, create a base layout that provides the base component to be wrapped by the BrowserRouter component:

      ~/djangoreactproject/frontend/src/App.js

      ...
      
      const  BaseLayout  = () => (
      <div  className="container-fluid">
          <nav  className="navbar navbar-expand-lg navbar-light bg-light">
              <a  className="navbar-brand"  href="#">Django React Demo</a>
              <button  className="navbar-toggler"  type="button"  data-toggle="collapse"  data-target="#navbarNavAltMarkup"  aria-controls="navbarNavAltMarkup"  aria-expanded="false"  aria-label="Toggle navigation">
              <span  className="navbar-toggler-icon"></span>
          </button>
          <div  className="collapse navbar-collapse"  id="navbarNavAltMarkup">
              <div  className="navbar-nav">
                  <a  className="nav-item nav-link"  href="/">CUSTOMERS</a>
                  <a  className="nav-item nav-link"  href="http://www.digitalocean.com/customer">CREATE CUSTOMER</a>
              </div>
          </div>
          </nav>
          <div  className="content">
              <Route  path="/"  exact  component={CustomersList}  />
              <Route  path="/customer/:pk"  component={CustomerCreateUpdate}  />
              <Route  path="/customer/"  exact  component={CustomerCreateUpdate}  />
          </div>
      </div>
      )
      

      We use the Route component to define the routes of our application; the component the router should load once a match is found. Each route needs a path to specify the path to be matched and a component to specify the component to load. The exact property tells the router to match the exact path.

      Finally, create the App component, the root or top-level component of our React application:

      ~/djangoreactproject/frontend/src/App.js

      ...
      
      class  App  extends  Component {
      
      render() {
          return (
          <BrowserRouter>
              <BaseLayout/>
          </BrowserRouter>
          );
      }
      }
      export  default  App;
      

      We have wrapped the BaseLayout component with the BrowserRouter component since our app is meant to run in the browser.

      The completed file looks like this:

      ~/djangoreactproject/frontend/src/App.js

      import React, { Component } from 'react';
      import { BrowserRouter } from 'react-router-dom'
      import { Route, Link } from 'react-router-dom'
      
      import  CustomersList from './CustomersList'
      import  CustomerCreateUpdate  from './CustomerCreateUpdate'
      import './App.css';
      
      const BaseLayout = () => (
        <div className="container-fluid">
      <nav className="navbar navbar-expand-lg navbar-light bg-light">
        <a className="navbar-brand" href="#">Django React Demo</a>
        <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
          <span className="navbar-toggler-icon"></span>
        </button>
        <div className="collapse navbar-collapse" id="navbarNavAltMarkup">
          <div className="navbar-nav">
            <a className="nav-item nav-link" href="/">CUSTOMERS</a>
            <a className="nav-item nav-link" href="http://www.digitalocean.com/customer">CREATE CUSTOMER</a>
      
          </div>
        </div>
      </nav>  
      
          <div className="content">
            <Route path="/" exact component={CustomersList} />
            <Route path="/customer/:pk"  component={CustomerCreateUpdate} />
            <Route path="/customer/" exact component={CustomerCreateUpdate} />
      
          </div>
      
        </div>
      )
      
      class App extends Component {
        render() {
          return (
            <BrowserRouter>
              <BaseLayout/>
            </BrowserRouter>
          );
        }
      }
      
      export default App;
      

      After adding routing to our application, we are now ready to test the application. Navigate to http://localhost:3000. You should see the first page of the application:

      Application Home Page

      With this application in place, you now have the base for a CRM application.

      Conclusion

      In this tutorial, you created a demo application using Django and React. You used the Django REST framework to build the REST API, Axios to consume the API, and Bootstrap 4 to style your CSS. You can find the source code of this project in this GitHub repository.

      This tutorial setup used separate front-end and back-end apps. For a different approach to integrating React with Django, check this tutorial and this tutorial.

      For more information about building an application with Django, you can follow the Django development series. You can also look at the official Django docs.



      Source link

      How to Deploy a Symfony 4 Application to Production with LEMP on Ubuntu 18.04


      The author selected Software in the Public Interest Inc to receive a donation as part of the Write for DOnations program.

      Introduction

      Symfony is an open-source PHP framework with an elegant structure and a reputation for being a suitable framework to kick-start any project irrespective of its size. As a set of reusable components, its flexibility, architecture, and high performance make it a top choice for building a highly complex enterprise application.

      In this tutorial, you will deploy an existing, standard Symfony 4 application to production with a LEMP stack (Nginx, MySQL, and PHP) on Ubuntu 18.04, which will help you get started configuring the server and the structure of the framework. Nginx is a popular open-source, high-performance HTTP server with additional features including reverse proxy support. It has a good reputation and hosts some of the largest and highest traffic sites on the internet. If you choose to deploy your own Symfony application instead, you might have to implement extra steps depending on the existing structure of your application.

      Prerequisites

      To complete this tutorial, you will need:

      Step 1 — Creating a User and Database for the Application

      By following the instructions in the Prerequisites, you now have all the basic server dependencies required for the application installation. As every dynamic web application requires a database, you will create a user and properly configure a database for the application in this section.

      To create a MySQL database for our application and a user associated with it, you need to access the MySQL client using the MySQL root account:

      Enter the appropriate password, which should be the same password used when running mysql_secure_installation.

      Next, create the application database with:

      You will see the following output in the console:

      Output

      Query OK, 1 row affected (0.00 sec)

      You have successfully created your application database. You can now create a MySQL user and grant them access to the newly created database.

      Execute the following command to create a MySQL user and password. You can change the username and password to something more secure if you wish:

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

      You will see the following output:

      Output

      Query OK, 0 rows affected (0.00 sec)

      Currently, the user blog-admin does not have the right permission over the application database. In fact, even if blog-admin tries to log-in with their password, they will not be able to reach the MySQL shell.

      A user needs the right permission before accessing or carrying out a specific action on a database. Use the following command to allow complete access to the blog database for the blog-admin user:

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

      You will see the following output:

      Output

      Query OK, 0 rows affected (0.00 sec)

      The blog-admin now has all privileges on all the tables inside the blog database. To reload the grant tables and apply changes, you need to perform a flush-privilege operation 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’re on track, exit the MySQL client:

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

      Check that the database can be accessed by the user with:

      You'll see the blog table in the output:

      Output

      +--------------------+ | Database | +--------------------+ | information_schema | | blog | +--------------------+ 2 rows in set (0.00 sec)

      Finally, exit the MySQL client:

      You have successfully created a database, a user for the demo application, and granted the newly created user the right privileges to access the database. You are now ready to set up the demo application.

      Step 2 — Setting Up the Demo Application

      To keep this tutorial simple, you will deploy a blog application built with Symfony. This application will allow an authenticated user to create a blog post and store it in the database. In addition, the application user can view all the posts and details associated with an author.

      The source code of the blog application you will deploy in this tutorial is on GitHub. You will use Git to pull the source code of the application from GitHub and save it in a new directory.

      First, create a directory that will serve as the root directory for your application. So, run the following command from the console to create a new directory named symfony-blog:

      • sudo mkdir -p /var/www/symfony-blog

      In order to work with the project files using a non-root user account, you’ll need to change the folder owner and group by running:

      • sudo chown sammy:sammy /var/www/symfony-blog

      Replace sammy with your sudo non-root username.

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

      • cd /var/www
      • git clone https://github.com/yemiwebby/symfony-blog.git symfony-blog

      You'll see the following output:

      Output

      Cloning into 'symfony-blog'... remote: Counting objects: 180, done. remote: Compressing objects: 100% (122/122), done. remote: Total 180 (delta 57), reused 164 (delta 41), pack-reused 0 Receiving objects: 100% (180/180), 167.01 KiB | 11.13 MiB/s, done. Resolving deltas: 100% (57/57), done.

      The demo application is now set. In the next step, you will configure the environment variables and install the required dependencies for the project.

      Step 3 — Configuring your Environment Variables for the Application

      To completely set up the application, you need to install the project dependencies and properly configure the application parameters.

      By default, the Symfony application runs in a development mode, which gives it a very detailed log for the purposes of debugging. This is not applicable to what you are doing in this tutorial, and not good practice for a production environment, as it can slow things down and create very large log files.

      Symfony needs to be aware that you’re running the application in a production environment. You can set this up by either creating a .env file containing variable declarations, or creating environment variables directly. Since you can also use the .env file to configure your database credentials for this application, it makes more sense for you to do this. Change your working directory to the cloned project and create the .env file with:

      • cd symfony-blog
      • sudo nano .env

      Add the following lines to the file to configure the production application environment:

      .env

      APP_ENV=prod
      APP_DEBUG=0
      

      APP_ENV is an environment variable that specifies that the application is in production, while APP_DEBUG is an environment variable that specifies if the application should run in debug mode or not. You have set it to false for now.

      Save the file and exit the editor.

      Next, install a PHP extension that Symfony apps use to handle XML:

      • sudo apt install php7.2-xml

      Next, you need to install the project dependencies, run composer install:

      • cd /var/www/symfony-blog
      • composer install

      You have successfully configured the environment variables and installed the required dependencies for the project. Next, you will set up the database credentials.

      Step 4 — Setting Up Database Credentials

      In order to retrieve data from the application’s database you created earlier, you will need to set up and configure the required database credentials from within the Symfony application.

      Open the .env file again:

      Add the following content to the file, which will allow you to easily connect and interact properly with the database. You can add it right after the APP_DEBUG=0 line within the .env file:

      .env

      ...
      DATABASE_URL=mysql://blog-admin:password@localhost:3306/blog
      

      The Symfony framework uses a third-party library called Doctrine to communicate with databases. Doctrine gives you useful tools to make interactions with databases easy and flexible.

      You can now use Doctrine to update your database with the tables from the cloned Github application. Run this command to do that:

      • php bin/console doctrine:schema:update --force

      You'll see the following output:

      Output

      Updating database schema... 4 queries were executed [OK] Database schema updated successfully!

      After setting up the required credentials and updating the database schema, you can now easily interact with the database. In order to start the application with some data, you will load a set of dummy data into the database in the next section.

      Step 5 — Populating your Database Using Doctrine-Fixtures

      At the moment, the newly created tables are empty. You will populate it using doctrine-fixtures. Using Doctrine-Fixtures is not a prerequisite for Symfony applications, it is only used to provide dummy data for your application.

      Run the following command to automatically load testing data that contains the details of an author and a sample post into the database table created for the blog:

      • php bin/console doctrine:fixtures:load

      You will get a warning about the database getting purged. You can go ahead and type Y:

      Output

      Careful, database will be purged. Do you want to continue y/N ? y > purging database > loading AppDataFixturesORMFixtures

      In the next section you will clear and warm up you cache.

      Step 6 — Clearing and Warming Up your Cache

      To ensure your application loads faster when users make requests, it is good practice to warm the cache during the deployment. Warming up the cache generates pages and stores them for faster responses later rather than building completely new pages. Fortunately, Symfony has a command to clear the cache that also triggers a warm up. Run the following command for that purpose:

      • php bin/console cache:clear

      You will see the following output:

      Output

      Clearing the cache for the prod environment with debug false [OK] Cache for the "prod" environment (debug=false) was successfully cleared.

      You will conclude the set up in a bit. All that remains is to configure the web server. You will do that in the next section.

      Step 7 — Configuring the Web Server and Running the Application

      By now, you have Nginx installed to serve your pages and MySQL to store and manage your data. You will now configure the web server by creating a new application server block, instead of editing the default one.

      Open a new server block with:

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

      Add the following content to the new server block configuration file. Ensure you replace the your_server_ip within the server block with your server IP address:

      /etc/nginx/sites-available/blog

      
      server {
          listen 80;
          listen [::]:80;
      
          server_name blog your_server_ip;
          root /var/www/symfony-blog/public;
          index index.php;
          client_max_body_size 100m;
      
          location / {
              try_files $uri $uri/ /index.php$is_args$args;
          }
      
          location ~ .php {
              try_files $uri /index.php =404;
              fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
              fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
              fastcgi_param SCRIPT_NAME $fastcgi_script_name;
              fastcgi_split_path_info ^(.+.php)(/.+)$;
              fastcgi_index index.php;
              include fastcgi_params;
            }
      
          location ~ /.(?:ht|git|svn) {
              deny all;
          }
      }
      

      First, we specified the listen directives for Nginx, which is by default on port 80, and then set the server name to match requests for the server’s IP address. Next, we used the root directives to specify the document root for the project. The symfony-blog application is stored in /var/www/symfony-blog, but to comply with best practices, we set the web root to /var/www/symfony-blog/public as only the /public subdirectory should be exposed to the internet. Finally, we configured the location directive to handle PHP processing.

      After adding the content, save the file and exit the editor.

      Note: If you created the file example.com in the prerequisite article How To Install Linux, Nginx, MySQL, PHP (LEMP stack) on Ubuntu 18.04, remove it from the sites-enabled directory with sudo rm /etc/nginx/sites-enabled/example.com so it doesn't conflict with this new file.

      To enable the newly created server block, we need to create a symbolic link from the new server block configuration file located in /etc/nginx/sites-available directory to the /etc/nginx/sites-enabled by using the following command:

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

      Check the new configuration file for any syntax errors by running:

      This command will print errors to the console if there are any. Once there are no errors run this command to reload Nginx:

      • sudo systemctl reload nginx

      You just concluded the last step required to successfully deploy the Symfony 4 application. You configured the web server by creating a server block and properly set the web root in order to make the web application accessible.

      Finally, you can now run and test out the application. Visit http://your_server_ip in your favorite browser:

      The following image is the screenshot of the Symfony blog application that you should see at your server's IP address:

      Alt screenshot of the Symfony blog application

      Conclusion

      Symfony is a feature-rich PHP framework with an architecture that makes web development fun for the developer who builds software using it. Symfony is a feature-rich web development framework that provides developers powerful tools to build web applications. It's often considered a good choice for enterprise applications due to its flexibility. The steps to deploy a typical Symfony application vary—depending on the setup, complexity, and the requirements of the application.

      In this tutorial, you manually deployed a Symfony 4 application to production on an Ubuntu 18.04 server running LEMP. You can now apply this knowledge to deploying your own Symfony applications.



      Source link