One place for hosting & domains

      Application

      How To Deploy a React Application with Nginx on Ubuntu 20.04


      The author selected Creative Commons to receive a donation as part of the Write for DOnations program.

      Introduction

      You can quickly deploy React applications to a server using the default Create React App build tool. The build script compiles the application into a single directory containing all of the JavaScript code, images, styles, and HTML files. With the assets in a single location, you can deploy to a web server with minimal configuration.

      In this tutorial, you’ll deploy a React application on your local machine to an Ubuntu 20.04 server running Nginx. You’ll build an application using Create React App, use an Nginx config file to determine where to deploy files, and securely copy the build directory and its contents to the server. By the end of this tutorial, you’ll be able to build and deploy a React application.

      Prerequisites

      • On your local machine, you will need a development environment running Node.js; this tutorial was tested on Node.js version 10.22.0 and npm version 6.14.6. To install this on macOS or Ubuntu 20.04, follow the steps in How to Install Node.js and Create a Local Development Environment on macOS or the Installing Using a PPA section of How To Install Node.js on Ubuntu 20.04.

      • One Ubuntu 20.04 server for deployment, set up by following this initial server setup for Ubuntu 20.04 tutorial, including a sudo-enabled non-root user, a firewall, and SSH access from your local machine. To gain SSH access on a DigitalOcean Droplet, read through How to Connect to Droplets with SSH.

      • A registered domain name. This tutorial will use your_domain throughout. You can purchase a domain name from Namecheap, get one for free with Freenom, or use the domain registrar of your choice.

      • Both of the following DNS records set up for your server. If you are using DigitalOcean, please see our DNS documentation for details on how to add them.

        • An A record with your_domain pointing to your server’s public IP address.
        • An A record with www.your_domain pointing to your server’s public IP address.
      • Nginx installed by following How To Install Nginx on Ubuntu 20.04. Be sure that you have a server block for your domain. This tutorial will use /etc/nginx/sites-available/your_domain as an example.

      • It is recommended that you also secure your server with an HTTPS certificate. You can do this with the How To Secure Nginx with Let’s Encrypt on Ubuntu 20.04 tutorial.

      • You will also need a basic knowledge of JavaScript, HTML, and CSS, which you can find in our How To Build a Website With HTML series, How To Build a Website With CSS series, and in How To Code in JavaScript.

      Step 1 — Creating a React Project

      In this step, you’ll create an application using Create React App and build a deployable version of the boilerplate app.

      To start, create a new application using Create React App in your local environment. In a terminal, run the command to build an application. In this tutorial, the project will be called react-deploy:

      • npx create-react-app react-deploy

      The npx command will run a Node package without downloading it to your machine. The create-react-app script will install all of the dependencies needed for your React app and will build a base project in the react-deploy directory. For more on Create React App, check out out the tutorial How To Set Up a React Project with Create React App.

      The code will run for a few minutes as it downloads and installs the dependencies. When it is complete, you will receive a success message. Your version may be slightly different if you use yarn instead of npm:

      Output

      Success! Created react-deploy at your_file_path/react-deploy Inside that directory, you can run several commands: npm start Starts the development server. npm build Bundles the app into static files for production. npm test Starts the test runner. npm eject Removes this tool and copies build dependencies, configuration files and scripts into the app directory. If you do this, you can’t go back! We suggest that you begin by typing: cd react-deploy npm start Happy hacking!

      Following the suggestion in the output, first move into the project folder:

      Now that you have a base project, run it locally to test how it will appear on the server. Run the project using the npm start script:

      When the command runs, you’ll receive output with the local server info:

      Output

      Compiled successfully! You can now view react-deploy in the browser. Local: http://localhost:3000 On Your Network: http://192.168.1.110:3000 Note that the development build is not optimized. To create a production build, use npm build.

      Open a browser and navigate to http://localhost:3000. You will be able to access the boilerplate React app:

      React project template running locally

      Stop the project by entering either CTRL+C or ⌘+C in a terminal.

      Now that you have a project that runs successfully in a browser, you need to create a production build. Run the create-react-app build script with the following:

      This command will compile the JavaScript and assets into the build directory. When the command finishes, you will receive some output with data about your build. Notice that the filenames include a hash, so your output will be slightly different:

      Output

      Creating an optimized production build... Compiled successfully. File sizes after gzip: 41.21 KB build/static/js/2.82f639e7.chunk.js 1.4 KB build/static/js/3.9fbaa076.chunk.js 1.17 KB build/static/js/runtime-main.1caef30b.js 593 B build/static/js/main.e8c17c7d.chunk.js 546 B build/static/css/main.ab7136cd.chunk.css The project was built assuming it is hosted at /. You can control this with the homepage field in your package.json. The build folder is ready to be deployed. You may serve it with a static server: serve -s build Find out more about deployment here: https://cra.link/deployment

      The build directory will now include compiled and minified versions of all the files you need for your project. At this point, you don’t need to worry about anything outside of the build directory. All you need to do is deploy the directory to a server.

      In this step, you created a new React application. You verified that the application runs locally and you built a production version using the Create React App build script. In the next step, you’ll log onto your server to learn where to copy the build directory.

      Step 2 — Determining Deployment File Location on your Ubuntu Server

      In this step, you’ll start to deploy your React application to a server. But before you can upload the files, you’ll need to determine the correct file location on your deployment server. This tutorial uses Nginx as a web server, but the approach is the same with Apache. The main difference is that the configuration files will be in a different directory.

      To find the directory the web server will use as the root for your project, log in to your server using ssh:

      Once on the server, look for your web server configuration in /etc/nginx/sites-enabled. There is also a directory called sites-allowed; this directory includes configurations that are not necessarily activated. Once you find the configuration file, display the output in your terminal with the following command:

      • cat /etc/nginx/sites-enabled/your_domain

      If your site has no HTTPS certificate, you will receive a result similar to this:

      Output

      server { listen 80; listen [::]:80; root /var/www/your_domain/html; index index.html index.htm index.nginx-debian.html; server_name your_domain www.your_domain; location / { try_files $uri $uri/ =404; } }

      If you followed the Let’s Encrypt prerequisite to secure your Ubuntu 20.04 server, you will receive this output:

      Output

      server { root /var/www/your_domain/html; index index.html index.htm index.nginx-debian.html; server_name your_domain www.your_domain; location / { try_files $uri $uri/ =404; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/your_domain/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/your_domain/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.your_domain) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = your_domain) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; listen [::]:80; server_name your_domain www.your_domain; return 404; # managed by Certbot }

      In either case, the most important field for deploying your React app is root. This points HTTP requests to the /var/www/your_domain/html directory. That means you will copy your files to that location. In the next line, you can see that Nginx will look for an index.html file. If you look in your local build directory, you will see an index.html file that will serve as the main entry point.

      Log off the Ubuntu 20.04 server and go back to your local development environment.

      Now that you know the file location that Nginx will serve, you can upload your build.

      Step 3 — Uploading Build Files with scp

      At this point, your build files are ready to go. All you need to do is copy them to the server. A quick way to do this is to use scp to copy your files to the correct location. The scp command is a secure way to copy files to a remote server from a terminal. The command uses your ssh key if it is configured. Otherwise, you will be prompted for a username and password.

      The command format will be scp files_to_copy username@server_ip:path_on_server. The first argument will be the files you want to copy. In this case, you are copying all of the files in the build directory. The second argument is a combination of your credentials and the destination path. The destination path will be the same as the root in your Nginx config:/var/www/your_domain/html.

      Copy all the build files using the * wildcard to /var/www/your_domain/html:

      • scp -r ./build/* username@server_ip:/var/www/your_domain/html

      When you run the command, you will receive output showing that your files are uploaded. Your results will be slightly different:

      Output

      asset-manifest.json 100% 1092 22.0KB/s 00:00 favicon.ico 100% 3870 80.5KB/s 00:00 index.html 100% 3032 61.1KB/s 00:00 logo192.png 100% 5347 59.9KB/s 00:00 logo512.png 100% 9664 69.5KB/s 00:00 manifest.json 100% 492 10.4KB/s 00:00 robots.txt 100% 67 1.0KB/s 00:00 main.ab7136cd.chunk.css 100% 943 20.8KB/s 00:00 main.ab7136cd.chunk.css.map 100% 1490 31.2KB/s 00:00 runtime-main.1caef30b.js.map 100% 12KB 90.3KB/s 00:00 3.9fbaa076.chunk.js 100% 3561 67.2KB/s 00:00 2.82f639e7.chunk.js.map 100% 313KB 156.1KB/s 00:02 runtime-main.1caef30b.js 100% 2372 45.8KB/s 00:00 main.e8c17c7d.chunk.js.map 100% 2436 50.9KB/s 00:00 3.9fbaa076.chunk.js.map 100% 7690 146.7KB/s 00:00 2.82f639e7.chunk.js 100% 128KB 226.5KB/s 00:00 2.82f639e7.chunk.js.LICENSE.txt 100% 1043 21.6KB/s 00:00 main.e8c17c7d.chunk.js 100% 1045 21.7KB/s 00:00 logo.103b5fa1.svg 100% 2671 56.8KB/s 00:00

      When the command completes, you are finished. Since a React project is built of static files that only need a browser, you don’t have to configure any further server-side language. Open a browser and navigate to your domain name. When you do, you will find your React project:

      Browser with React Project on Server

      In this step, you deployed a React application to a server. You learned how to identify the root web directory on your server and you copied the files with scp. When the files finished uploading, you were able to view your project in a web browser.

      Conclusion

      Deploying React applications is a quick process when you use Create React App. You run the build command to create a directory of all the files you need for a deployment. After running the build, you copy the files to the correct location on the server, pushing your application live to the web.

      If you would like to read more React tutorials, check out our React Topic page, or return to the How To Code in React.js series page.



      Source link

      How To Deploy a React Application to DigitalOcean App Platform


      The author selected Creative Commons to receive a donation as part of the Write for DOnations program.

      Introduction

      DigitalOcean’s App Platform is a Platform as a Service (PaaS) product that lets you configure and deploy applications from a source repository. After configuring your app, DigitalOcean will build and deploy the application on every change, giving you the benefit of a full web server and deployment pipeline with minimal configuration. This can be a quick and efficient way to deploy your React applications, and if you are using React to build a site with no backend, you can use App Platform’s free tier.

      In this tutorial, you’ll deploy a React application to the DigitalOcean App Platform using the free Starter tier. You’ll build an application with Create React App, push the code to a GitHub repository, then configure the application as a DigitalOcean app. You’ll connect the app to your source code and deploy the project as a set of static files.

      By the end of this tutorial, you’ll be able to configure a React application to deploy automatically on every push to the main branch of a GitHub repository.

      Prerequisites

      Step 1 — Creating a React Project

      In this step, you’ll create a React application using Create React App and build a deployable version of it.

      To start, create a new application using Create React App on your local machine. In a terminal, run the command to build an application called digital-ocean-app:

      • npx create-react-app digital-ocean-app

      The npx command will run a Node package without downloading it to your machine. The create-react-app script will install all of the dependencies and will build a base project in the digital-ocean-app directory. For more on Create React App, check out the tutorial How To Set Up a React Project with Create React App.

      The code will download the dependencies and will create a base project. It may take a few minutes to finish. When it is complete, you will receive a success message. Your version may be slightly different if you use yarn instead of npm:

      Output

      Success! Created digital-ocean-app at your_file_path/digital-ocean-app Inside that directory, you can run several commands: npm start Starts the development server. npm build Bundles the app into static files for production. npm test Starts the test runner. npm eject Removes this tool and copies build dependencies, configuration files and scripts into the app directory. If you do this, you can’t go back! We suggest that you begin by typing: cd digital-ocean-app npm start Happy hacking!

      Now that you have a base project, run it locally so you can test how the project will appear on the server. First, change into the directory:

      Run the project using the npm start script:

      When the command runs, you’ll receive output with the URL for the local development server:

      Output

      Compiled successfully! You can now view digital-ocean-app in the browser. Local: http://localhost:3000 On Your Network: http://192.168.1.110:3000 Note that the development build is not optimized. To create a production build, use npm build.

      Open a browser to http://localhost:3000 and you’ll find your project:

      React project template running locally

      Stop the project by typing either CTRL+C or ⌘+C in the terminal.

      Now that you have a working React application, you can push the code to a GitHub repository.

      Step 2 — Pushing the Code to GitHub

      To deploy your app, App Platform retrieves your source code from a hosted code repository. In this step, you will push your React app code to a GitHub repository so that App Platform can access it later.

      Log in to your GitHub account. After you log in, create a new repository called digital-ocean-app. You can make the repository either private or public:

      New GitHub repository page

      Create React App automatically initializes your project with git, so you can set up to push the code directly to GitHub. First, add the repository that you’d like to use with the following command:

      • git remote add origin git@github.com:your_name/digital-ocean-app.git

      Next, declare that you want to push to the main branch with the following:

      Finally, push the code to your repository:

      Enter your GitHub credentials when prompted to push your code.

      When you push the code you will receive a success message. Your message will be slightly different:

      Output

      Counting objects: 22, done. Delta compression using up to 4 threads. Compressing objects: 100% (22/22), done. Writing objects: 100% (22/22), 187.50 KiB | 6.94 MiB/s, done. Total 22 (delta 0), reused 0 (delta 0) To github.com:your_name/digital-ocean-app.git 4011c66..647d2e1 main -> main

      You’ve now copied your code to the GitHub repository.

      In this step, you pushed your project to GitHub so that you can access it using DigitalOcean Apps. Next, you’ll create a new DigitalOcean App using your project and set up automatic deployment.

      Step 3 — Deploying to DigitalOcean App Platform

      In this step, you’ll deploy a React application to the DigitalOcean App Platform. You’ll connect your GitHub repository to DigitalOcean, configure the project to build, and build your initial project. After the project is live, each change will trigger a new build and update.

      By the end of this step, you’ll be able to deploy an application with continous delivery on DigitalOcean.

      To begin, log in to your DigitalOcean account and press the Create button, then select Apps:

      Create a new app page in the DigitalOcean interface

      You’ll next be prompted to link your GitHub repository. If you have not yet connected it, you will need to log in with your username and password and give DigitalOcean authorization to access your repositories:

      Link GitHub to DigitalOcean page

      Once you link your account, select the repository you’d like to connect on the GitHub authorization screen. In this case, you are using the digital-ocean-app repository, but you can connect more repositories if you would like:

      Select a repo on GitHub authorization page

      After selecting the repository, you will reconnect to the DigitalOcean interface. Select digital-ocean-app from the list of repositories, then press Next. This will connect your App directly to the GitHub repo:

      Select repo in the DigitalOcean UI

      Now that you have selected your repository, you need to configure the DigitalOcean App. In this example, the server will be based in North America by choosing New York in the Region field, and the deployment branch will be main. For your app, choose the region that is closest to your physical location:

      Select branch and location in the DigitalOcean interface

      For this tutorial, you are checking Autodeploy code changes. This will automatically rebuild your app every time you update the code.

      Press Next to move on to the Configure your app screen.

      Next, select the type of application you will run. Since React will build static assets, select Static Site from the dropdown menu in the Type field.

      Note: Create React App is not a static site generator like Gatsby, but you are using static assets, since the server does not need to run any server-side code such as Ruby or PHP. The app will use Node to run the install and build steps, but will not execute application code at the free tier.

      You also have the option to use a custom build script. But in this case, you can stick with the default npm run build command. You may want to create a custom build script if you have a different build script for a quality assurance (QA) or a production environment:

      Select Static Site on the app configuration page

      Press Next to move on to the Finalize and launch page.

      Here you can select the price plan. The free Starter tier is made for static sites, so choose that one:

      Select price option for DigitalOcean App Platform

      Press the Launch Starter App button and DigitalOcean will start building your application.

      DigitalOcean is building the application page

      The app will run the npm ci and npm build scripts in your repo. This will download all of the dependencies and create the build directory with a compiled and minified version of all of your JavaScript, HTML files, and other assets. You could also create a custom script in your package.json and update the Commands in the Components tab of your application on App Platform.

      It will take a few minutes for the build to run, but when it is finished, you will receive a success message and a link to your new site. Your link will have a unique name and will be slightly different:

      Deploy complete page

      Press Live App to access your project in the browser. It will be the same as the project you tested locally, but this will be live on the web with a secure URL:

      Live application

      Now that your project is configured, any time you make a change to the linked repository, you’ll run a new build. In this case, if you push a change to the main branch, DigitalOcean will automatically run a new deployment. There is no need to log in; it will run as soon as you push the change:

      New deploy

      In this step, you created a new DigitalOcean app on App Platform. You connected your GitHub account and configured the app to build the main branch. After configuring the application, you learned that the app will deploy a new build after every change.

      Conclusion

      DigitalOcean’s App Platform gives you a quick tool for deploying applications. With a small initial set up, your app will deploy automatically after every change. This can be used in conjunction with React to quickly get your web application up and running.

      A possible next step for a project like this would be to change the domain name of the app. To do this, take a look at the official documentation for App Platform.



      Source link

      How To Bootstrap a New Laravel Application with Docker Compose



      Part of the Series:
      How To Build a Links Landing Page in PHP with Laravel and Docker Compose

      Laravel is an open-source PHP framework that provides a set of tools and resources to build modern PHP applications. In this project-based tutorial series, you’ll build a Links Landing Page application with the Laravel framework, using a containerized PHP development environment managed by Docker Compose.

      At the end, you’ll have a one-page website built with Laravel and managed via Artisan commands where you can share relevant links to an audience on social channels and presentations.

      To get started, you’ll need to create a containerized environment able to execute PHP and Composer, the PHP dependency management tool. Then, you’ll be able to bootstrap the new Laravel application from scratch, without the need to have a local PHP environment installed on your local machine or development server.

      In this guide, we’ll provide streamlined instructions on how to set this environment up based on our tutorial on How To Install Laravel with Docker Compose on Ubuntu 20.04. Please refer to that tutorial for more detailed instructions on each of the options used within the Docker Compose file that will be provided in this guide.

      Create a new directory for your application in your home folder:

      • mkdir ~/landing-laravel
      • cd ~/landing-laravel

      Next, you’ll create the docker-compose.yml file that will define the containerized environment. In this file, you’ll set up a service named app, which will be based on a custom Docker image built with a Dockerfile you’ll set up later on.

      The build arguments user and uid, both defined in the docker-compose.yml file and used in the Dockerfile at build time, should be changed to reflect your own username and uid on your local machine or development server. To find out your current user’s uid, type:

      Output

      1000

      The user and uid variables will be available at build time and will be used in the Dockerfile to create a new user in the app service with the same username and uid as your current system user on your local machine or development server. This will avoid permission and ownership issues when working with application files both from the container as well as from the host that executes Docker.

      Create a new docker-compose.yml file using your text editor of choice. Here, we’re using nano:

      Copy the following content to this file, and don’t forget to replace the highlighted values with appropriate values depending on your own username and uid on the system that runs Docker:

      ~/landing-laravel/docker-compose.yml

      version: "3.7"
      services:
        app:
          build:
            args:
              user: sammy
              uid: 1000
            context: ./
            dockerfile: Dockerfile
          image: landing-app
          restart: unless-stopped
          working_dir: /var/www/
          volumes:
            - ./:/var/www
          networks:
            - landing
      
      networks:
        landing:
          driver: bridge
      

      Save and close the file when you are done. If you are using nano, you can do that by pressing CTRL+X, then Y and ENTER to confirm.

      Next, you’ll set up the Dockerfile that is referenced in the docker-compose.yml file, which will set up a custom image for the app service:

      This Dockerfile extends from the default php:7.4-fpm Docker image. It uses the user and uid variables to create a new user able to execute Artisan and Composer commands. It also installs a few PHP dependencies that are required by Laravel, and the Composer executable.

      Copy the following content to your Dockerfile:

      ~/my-todo-list/Dockerfile

      FROM php:7.4-fpm
      
      # Arguments defined in docker-compose.yml
      ARG user
      ARG uid
      
      # Install system dependencies
      RUN apt-get update && apt-get install -y 
          git 
          curl 
          libpng-dev 
          libonig-dev 
          libxml2-dev 
          zip 
          unzip
      
      # Clear cache
      RUN apt-get clean && rm -rf /var/lib/apt/lists/*
      
      # Install PHP extensions
      RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd
      
      # Get latest Composer
      COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
      
      # Create system user to run Composer and Artisan Commands
      RUN useradd -G www-data,root -u $uid -d /home/$user $user
      RUN mkdir -p /home/$user/.composer && 
          chown -R $user:$user /home/$user
      
      # Set working directory
      WORKDIR /var/www
      
      USER $user
      

      Save and close the file when you’re done. Next, you can bring your environment up with:

      This command will execute Docker Compose in detached mode, which means it will run in the background. The first time you bring an environment up with a custom image, Docker Compose will automatically build the image for you before creating the required containers. This might take a few moments to finish. You’ll see output similar to this:

      Output

      Creating network "landing-laravel_landing" with driver "bridge" Building app Step 1/11 : FROM php:7.4-fpm ---> fa37bd6db22a ... Step 10/11 : WORKDIR /var/www ---> Using cache ---> 769afd5d44d8 Step 11/11 : USER $user ---> Using cache ---> 841eb5852b69 Successfully built 841eb5852b69 Successfully tagged landing-app:latest WARNING: Image for service app was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`. Creating landing-laravel_app_1 ... done

      You can verify that your environment is up and running with:

      Output

      Name Command State Ports ------------------------------------------------------------------------ landing-laravel_app_1 docker-php-entrypoint php-fpm Up 9000/tcp

      Once the app service is up, you can run Composer, the PHP dependency management tool, to bootstrap a new Laravel application. In order to do that, you’ll use docker compose exec to run commands on the app service, where PHP is installed.

      The following command will use Docker Compose to execute composer create-project, which will bootstrap a fresh installation of Laravel based on the laravel/laravel package:

      • docker-compose exec app composer create-project laravel/laravel --prefer-dist application
      Creating a "laravel/laravel" project at "./application"
      Installing laravel/laravel (v8.4.0)
        - Downloading laravel/laravel (v8.4.0)
        - Installing laravel/laravel (v8.4.0): Extracting archive
      Created project in /var/www/application
      > @php -r "file_exists('.env') || copy('.env.example', '.env');"
      Loading composer repositories with package information
      Updating dependencies
      Lock file operations: 104 installs, 0 updates, 0 removals
      …
      Package manifest generated successfully.
      71 packages you are using are looking for funding.
      Use the `composer fund` command to find out more!
      > @php artisan key:generate --ansi
      Application key set successfully.
      

      This installation creates a new .env file based on the default .env.example file that comes with Laravel. The .env file contains database credentials and other sensitive application settings, and should be unique per environment where the app runs. You’ll come back to edit this file after you finish setting up the development environment.

      Next, copy the application files to the same directory as the docker-compose.yml file, so that you can share Laravel’s environment variables file with Docker Compose. Then, you can remove the application directory created by Composer:

      cp -rT application .
      rm -rfv application
      

      Your application is now bootstrapped, but you’ll need to include a couple services in the Docker Compose file in order to be able to access the app from a browser. An nginx service will serve the application using the Nginx web server, and a db service will host the application’s MySQL database.

      First, bring your environment down with:

      Output

      Stopping landing-laravel_app_1 ... done Removing landing-laravel_app_1 ... done Removing network landing-laravel_landing

      This will remove all containers and networks associated with this environment. Before editing your docker-compose.yml file to add the new services, create a new directory to share configuration files with containers. You’ll need this to properly set up Nginx to handle the Laravel PHP application.

      • mkdir -p docker-compose/nginx

      Next, create a new landing-laravel.conf file containing a custom Nginx server block. Later on, you’ll set up a volume to share this file within the nginx service container.

      Open a new Nginx configuration file with:

      • nano docker-compose/nginx/landing-laravel.conf

      The following server block configures Nginx to serve a Laravel application using an external service (app) to handle PHP code. Copy this content to your own Nginx configuration file:

      docker-compose/nginx/landing-laravel.conf

      server {
          listen 80;
          index index.php index.html;
          error_log  /var/log/nginx/error.log;
          access_log /var/log/nginx/access.log;
          root /var/www/public;
          location ~ .php$ {
              try_files $uri =404;
              fastcgi_split_path_info ^(.+.php)(/.+)$;
              fastcgi_pass app:9000;
              fastcgi_index index.php;
              include fastcgi_params;
              fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
              fastcgi_param PATH_INFO $fastcgi_path_info;
          }
          location / {
              try_files $uri $uri/ /index.php?$query_string;
              gzip_static on;
          }
      }
      

      Save and close the file when you’re done.

      Next, open your docker-compose.yml file:

      Include the following configuration for the nginx service, at the same level as the previously configured app service. This will create a new service based on the nginx:alpine image, and all requests on port 8000 of the host where Docker is running will be redirected to port 80 in the service container. In addition to the application files, you’ll also share a volume containing Nginx’s configuration file for a Laravel application:

        nginx:
          image: nginx:alpine
          restart: unless-stopped
          ports:
            - 8000:80
          volumes:
            - ./:/var/www
            - ./docker-compose/nginx:/etc/nginx/conf.d/
          networks:
            - landing
      
      

      Then, include the following configuration block for the db service. This will create a service based on the default MySQL 8 image, and pull in the values defined in Laravel’s environment file to set up database access:

        db:
          image: mysql:8
          restart: unless-stopped
          environment:
            MYSQL_DATABASE: ${DB_DATABASE}
            MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
            MYSQL_PASSWORD: ${DB_PASSWORD}
            MYSQL_USER: ${DB_USERNAME}
          networks:
            - landing
      

      This is how your updated docker-compose.yml file should look like once you’re finished:

      ~/landing-laravel/docker-compose.yml

      version: "3.7"
      services:
        app:
          build:
            args:
              user: sammy
              uid: 1000
            context: ./
            dockerfile: Dockerfile
          image: landing-app
          restart: unless-stopped
          working_dir: /var/www/
          volumes:
            - ./:/var/www
          networks:
            - landing
      
        nginx:
          image: nginx:alpine
          restart: unless-stopped
          ports:
            - 8000:80
          volumes:
            - ./:/var/www
            - ./docker-compose/nginx:/etc/nginx/conf.d/
          networks:
            - landing
        db:
          image: mysql:8
          restart: unless-stopped
          environment:
            MYSQL_DATABASE: ${DB_DATABASE}
            MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
            MYSQL_PASSWORD: ${DB_PASSWORD}
            MYSQL_USER: ${DB_USERNAME}
          networks:
            - landing
      
      networks:
        landing:
          driver: bridge
      
      

      Note: for more detailed information about containerizing Laravel environments, including explanations about shared volumes and networks, please refer to our full guide on How To Install Laravel with Docker Compose on Ubuntu 20.04.

      Save and close the file when you’re done editing. Lastly, update your Laravel dot env file (.env) to point the MySQL database host configuration to the host where the MySQL service will be running, called db:

      The .env file that is automatically generated by Composer upon installation comes with some default values that you might want to change, such as the APP_NAME and the APP_URL. The database DB_HOST variable must be changed to point to the service where MySQL will be running, and you can reference it by its service name, as defined in the docker-compose.yml file. In this example, we’ve used db as name for the database service, so this will be available in the containerized network as a host named db.

      Change your .env accordingly, using the following example as base. The highlighted values were updated here to reflect the state of the application under development:

      ~/landing-laravel/.env

      APP_NAME=LandingLaravel
      APP_ENV=local
      APP_KEY=base64:ffYPNP8kPeQDf8gE/qh3kWjk59p6gFY66kCKhhKUa2w=
      APP_DEBUG=true
      APP_URL=http://localhost:8000
      
      LOG_CHANNEL=stack
      LOG_LEVEL=debug
      
      DB_CONNECTION=mysql
      DB_HOST=db
      DB_PORT=3306
      DB_DATABASE=landing-db
      DB_USERNAME=landing-user
      DB_PASSWORD=dev-password
      
      ...
      

      You don’t need to change any other sections of this file, but feel free to tweak to your specific use case.

      Save and close the file when you’re done editing its contents.

      You can now bring the updated environment up with:

      Output

      Creating network "landing-laravel_landing" with driver "bridge" Creating landing-laravel_app_1 ... done Creating landing-laravel_db_1 ... done Creating landing-laravel_nginx_1 ... done

      With the full environment up, you can now point your browser to localhost or your remote server’s IP address, on port 8000:

      http://localhost:8000
      

      If everything works as expected, you’ll see a page like this:

      Laravel Landing Links - basic app

      In the next part of this series, you’ll create a database migration to set up a links table.



      Source link