Installing the LEMP Stack on CentOS 8

Traducciones al Español
Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.
Create a Linode account to try this guide with a $ credit.
This credit will be applied to any valid services used during your first  days.

What is the LEMP Stack?

The LAMP stack (Linux, Apache, MariaDB, and PHP) is a popular server configuration for developing and hosting web applications. The four components of the stack are not tightly coupled, making it possible to substitute your preferred technologies. The LEMP stack is a common variant in which the Apache web server is replaced by NGINX, pronounced “engine-x”, thus providing the “E”.

Before You Begin

  1. If you have not already done so, create a Linode account and Compute Instance. See our Getting Started with Linode and Creating a Compute Instance guides.

  2. Follow our Setting Up and Securing a Compute Instance guide to update your system. You may also wish to set the timezone, configure your hostname, create a limited user account, and harden SSH access.

Note
If you have a registered domain name for your website, then add the domain to the Linode server on which you plan to install the LEMP stack. If you do not have a registered domain name, then replace example.com with the IP address of the Linode server in the following instructions.

Installation

NGINX

  1. Install NGINX from the package repository:

    sudo dnf install nginx
    
  2. Enable and start the NGINX service:

    sudo systemctl enable nginx
    sudo systemctl start nginx
    

MariaDB

MariaDB is a popular fork of MySQL, and its development is considered to be more open and transparent than MySQL’s. MariaDB is administered with the same commands as MySQL.

  1. Install the MariaDB server and MySQL/MariaDB-PHP support:

    sudo dnf install mariadb-server php-mysqlnd
    
  2. Set MariaDB to start at boot and start the daemon for the first time:

    sudo systemctl enable mariadb.service
    sudo systemctl start mariadb.service
    
  3. Log in to MariaDB’s SQL shell:

    mysql -u root
    
  4. Create a test database and user with access permission. Replace testdb and testuser with appropriate names for your setup. Replace password with a strong password.

    1
    2
    3
    
    CREATE DATABASE testdb;
    CREATE USER 'testuser' IDENTIFIED BY 'password';
    GRANT ALL PRIVILEGES ON testdb.* TO 'testuser';
  5. Exit the SQL shell:

    1
    
    quit
  6. Use the mysql_secure_installation tool to configure additional security options. You will be given the choice to change the MariaDB root password, remove anonymous user accounts, disable root logins outside of localhost, and remove test databases. It is recommended that you answer yes to these options. You can read more about the script in the MariaDB Knowledge Base.

    sudo mysql_secure_installation
    

PHP

  1. Install the PHP FastCGI Processing Manager, which includes the core PHP dependencies:

    sudo dnf install php-fpm
    
  2. Enable and start the php-fpm.service:

    sudo systemctl enable php-fpm.service
    sudo systemctl start php-fpm.service
    
  3. Change the default user in /etc/php-fpm.d/www.conf from apache to nginx:

    File: /etc/php-fpm.d/www.conf
    1
    2
    3
    4
    5
    6
    
    
    ; RPM: apache user chosen to provide access to the same directories as httpd
    user = nginx
    ; RPM: Keep a group allowed to write in log dir.
    group = nginx
    
  4. Tell PHP to only accept URIs for files that actually exist on the server. This mitigates a security vulnerability where the PHP interpreter can be tricked into allowing arbitrary code execution if the requested .php file is not present in the filesystem. See this tutorial for more information about this vulnerability.

    sudo sed -i 's/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/g' /etc/php.ini
    

Set an NGINX Site Configuration File

  1. Create a root directory where the site’s content will live. Replace example.com with your site’s domain.

     sudo mkdir -p /var/www/html/example.com/public_html
    
  2. Assign the ownership of the directory to $USER:

     sudo chown -R $USER:$USER /var/www/html/example.com/public_html
    
  3. Use SELinux’s chcon command to change the file security context for web content, replace example.com with your domain name:

    sudo chcon -t httpd_sys_content_t /var/www/html/example.com -R
    sudo chcon -t httpd_sys_rw_content_t /var/www/html/example.com -R
    
  4. Update the document root location of the web content in /etc/nginx/nginx.conf file.

    File: /etc/nginx/nginx.conf
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /var/www/html/example.com/public_html;
    
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
    
        location / {
        }
    
        error_page 404 /404.html;
            location = /40x.html {
        }
    
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
  5. Create a example.com.conf configuration file for your domain in etc/nginx/conf.d directory. Replace example.com with your domain in the contents of the file:

    File: /etc/nginx/conf.d/example.com.conf
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    
        server {
        listen         80;
        listen         [::]:80;
        server_name    example.com www.example.com;
        root           /var/www/html/example.com/public_html;
        index          index.html;
    
        location / {
          try_files $uri $uri/ =404;
        }
        location ~* \.php$ {
          fastcgi_pass unix:/run/php-fpm/www.sock;
          include         fastcgi_params;
          fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
          fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
        }
    }

Configure FirewallD

FirewallD is enabled for CentOS 8 Linodes, but HTTP and HTTPS are not included in the default set of services.

  1. View the default set of services:

     sudo firewall-cmd --zone=public --list-services
    
    cockpit dhcpv6-client ssh
  2. To allow connections to NGINX, add HTTP and HTTPS as a service:

     sudo firewall-cmd --zone=public --add-service=http --permanent
     sudo firewall-cmd --zone=public --add-service=https --permanent
     sudo firewall-cmd --reload
    
Note
In addition, if you plan to use any HTTPD scripts on the server, update the corresponding SELinux Boolean variable. To allow HTTPD scripts and modules to connect to the network, use sudo setsebool -P httpd_can_network_connect on command.

Test the LEMP Stack

  1. To ensure that your web server can be reached with your domain name, configure the DNS records for your domain to point to your Linode’s IP address.

  2. Restart PHP and reload the NGINX configuration:

    sudo systemctl restart php-fpm
    sudo nginx -s reload
    
  3. Test the NGINX configuration:

    sudo nginx -t
    
  4. Create a test page to verify NGINX can render PHP and connect to the MariaDB database. Replace the "testuser" and "password" fields with the MariaDB credentials you created above.

    File: /var/www/html/example.com/public_html/test.php
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    
    <html>
    <head>
        <h2>LEMP Stack Test</h2>
    </head>
        <body>
        <?php echo '<p>Hello,</p>';
    
        // Define PHP variables for the MySQL connection.
        $servername = "localhost";
        $username = "testuser";
        $password = "password";
    
        // Create a MySQL connection.
        $conn = mysqli_connect($servername, $username, $password);
    
        // Report if the connection fails or is successful.
        if (!$conn) {
            exit('<p>Your connection has failed.<p>' .  mysqli_connect_error());
        }
        echo '<p>You have connected successfully.</p>';
        ?>
    </body>
    </html>
    
  5. Go to http://example.com/test.php in a web browser. It should report that You have connected successfully.

    LEMP Stack Test Page Success

    If you see an error message or if the page does not load at all, re-check your configuration. If your DNS changes haven’t propagated yet, you can test your page with curl instead:

    curl -H "Host: example.com" http://<your-ip-address>/test.php
    
    1
    2
    3
    4
    5
    6
    7
    
    <html>
    <head>
    <h2>LEMP Stack Test</h2>
    </head>
    <body>
    <p>Hello,</p><p>You have connected successfully.</p></body>
    </html>
  6. Remove the test file once the stack is working correctly:

    sudo rm /var/www/html/example.com/public_html/test.php
    

Next Steps

For more on the software in this stack see the following guides:

This page was originally published on


Your Feedback Is Important

Let us know if this guide was helpful to you.


Join the conversation.
Read other comments or post your own below. Comments must be respectful, constructive, and relevant to the topic of the guide. Do not post external links or advertisements. Before posting, consider if your comment would be better addressed by contacting our Support team or asking on our Community Site.
The Disqus commenting system for Linode Docs requires the acceptance of Functional Cookies, which allow us to analyze site usage so we can measure and improve performance. To view and create comments for this article, please update your Cookie Preferences on this website and refresh this web page. Please note: You must have JavaScript enabled in your browser.