//------------------------------------------------------------------- //-------------------------------------------------------------------
How to Setup LEMP on Linux VPS

Build a High-Traffic LEMP Stack on Linux VPS: From Install to Optimization

In high-traffic web hosting, milliseconds matter. Standard LAMP stacks often struggle when too many users visit at once. This is why the LEMP on Linux VPS is superior. By switching from Apache to the faster Nginx web server, you can handle 4x the traffic using the same hardware.

In this guide, you will learn how to deploy and tune Nginx, MariaDB, and PHP on a Linux VPS running Ubuntu 24.04, which ensures your infrastructure is optimized for speed, security, and scalability.

Prerequisites to Set up LEMP on Linux VPS

To start setting up LEMP on Linux VPS, you need to ensure your environment is ready. Here is exactly what you need to get started:

  • Linux VPS: You will need a server running Ubuntu 24.04. If you don’t have one yet, you can deploy a high-performance Linux VPS at Perlod Hosting.
  • Root Access: Log in as root or a user with sudo privileges.
  • Clean System: A fresh installation to avoid conflicts.
  • Valid domain name points to your Linux VPS IP address.

Once you are done, proceed to the following steps to install LEMP on Linux VPS.

Install and Optimize Nginx

Nginx is preferred for high traffic because of its event-driven architecture. To install it on your Ubuntu system, run the system update and install Nginx with the commands below:

sudo apt update && sudo apt upgrade -y
sudo apt install nginx -y

For high traffic, you must adjust the Nginx worker processes and connection limits. Open the main Nginx config file with your desired text editor:

sudo nano /etc/nginx/nginx.conf

Modify or add these settings inside the events and http blocks:

user www-data;
worker_processes auto; # Automatically matches CPU cores
pid /run/nginx.pid;

events {
    worker_connections 4096; # Increased from default 768 for high concurrency
    multi_accept on;         # Accept as many connections as possible
}

http {
    ## Basic Settings
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 15;    # Reduced timeout to free up connections faster
    types_hash_max_size 2048;
    client_max_body_size 64M; # Allow larger file uploads

    ## Buffer Settings for Performance
    client_body_buffer_size 10K;
    client_header_buffer_size 1k;
    large_client_header_buffers 2 1k;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ## Logging Settings
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ## Gzip Settings
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}

Once you are done, save and close the file and restart Nginx to apply the changes:

sudo systemctl restart nginx

Install and Tune MariaDB

MariaDB is a drop-in MySQL replacement known for better performance. Use the command below to install it for LEMP on Linux VPS:

sudo apt install mariadb-server -y

Run the MySQL security script to remove insecure defaults:

sudo mysql_secure_installation

Answer Y to:

  • Switch to unix_socket authentication.
  • Change the root password.
  • Remove anonymous users.
  • Disallow root login remotely.
  • Remove the test database.
  • Reload privilege tables.

For optimizing MariaDB performance, create a custom configuration override file. Remember not to edit the default my.cnf.

sudo nano /etc/mysql/mariadb.conf.d/99-high-traffic.cnf

Add the following configurations to the file:

Note: Adjust innodb_buffer_pool_size to 70% of your total RAM.

[mysqld]
# Connection Settings
max_connections = 500       # Allow more simultaneous database connections
wait_timeout = 600          # Close idle connections to save resources

# InnoDB Settings (Critical for performance)
innodb_buffer_pool_size = 4G  # ADJUST THIS: Set to 70% of available RAM
innodb_log_file_size = 512M
innodb_flush_log_at_trx_commit = 2 # Boosts write speed (slight risk on power loss)
innodb_flush_method = O_DIRECT

# Query Cache (Disable for high concurrency)
query_cache_type = 0
query_cache_size = 0

Restart MariaDB to apply the changes:

sudo systemctl restart mariadb

Install and Configure PHP-FPM

As you must know, PHP-FPM handles the dynamic processing. Ubuntu 24.04 uses PHP 8.3 by default. To install PHP-FPM and extensions for LEMP on Linux VPS, run the command below:

sudo apt install php8.3-fpm php8.3-mysql php8.3-common php8.3-cli php8.3-opcache php8.3-xml php8.3-mbstring php8.3-curl -y

For high traffic, the default dynamic process manager is often too slow. Switch to static if you have plenty of RAM, or optimize the dynamic process manager.

Open the default PHP-FPM pool configuration:

sudo nano /etc/php/8.3/fpm/pool.d/www.conf

Find and modify these lines:

user = www-data
group = www-data

; Use 'static' for maximum performance if RAM permits. 
; Formula: (Total RAM - 1GB for OS/DB) / ~60MB per process
pm = static
pm.max_children = 50      ; Adjust based on your RAM (e.g., 50 for ~4GB RAM)
pm.max_requests = 1000    ; Restart processes after 1000 requests to prevent memory leaks

; Increase request termination timeout for heavy scripts
request_terminate_timeout = 60s

The value pm.max_children = 50 is a safe estimate for a 4GB server. If you set this too high, your server will crash. To calculate the exact number based on your specific RAM and process size, follow our dedicated guide on how to calculate PHP-FPM max_children.

Save and close the file and restart PHP-FPM to apply the changes:

sudo systemctl restart php8.3-fpm

Note: Heavy tasks exceeding 60 seconds may cause Nginx to drop connections. If you encounter 504 errors, follow our guide to fix Nginx upstream timeouts by adjusting your proxy settings.

Configure Nginx Server Block for LEMP Stack

Now that we have all the components installed, we need to tell Nginx how to use them. In this step, we will create an Nginx server block that configures your domain, defines where your website files are stored, and connects Nginx to the PHP-FPM processor.

Create a site configuration file with the command below:

sudo nano /etc/nginx/sites-available/your-domain.com

Paste the following configuration into the file:

server {
    listen 80;
    server_name your-domain.com www.your-domain.com;
    root /var/www/your-domain.com;
    index index.php index.html index.htm;

    # Logs
    access_log /var/log/nginx/your-domain_access.log;
    error_log /var/log/nginx/your-domain_error.log;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    # Pass PHP scripts to FastCGI server
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock; # Verify version match
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        
        # Performance Tweaks
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size 256k;
    }

    # Deny access to hidden files (.htaccess)
    location ~ /\.ht {
        deny all;
    }
}

Enable the site with the command below:

sudo ln -s /etc/nginx/sites-available/your-domain.com /etc/nginx/sites-enabled/

Test your syntax configuration and reload Nginx:

sudo nginx -t
sudo systemctl reload nginx

To verify the setup, you can create a PHP info file to confirm Nginx is handling PHP properly:

sudo mkdir -p /var/www/your-domain.com
echo "" | sudo tee /var/www/your-domain.com/info.php

Then, visit the URL below in your browser:

http://your-domain.com/info.php

You should see the PHP configuration page.

Security Note: Delete this file immediately after testing:

sudo rm /var/www/your-domain.com/info.php

You now have a fully tuned LEMP on Linux VPS ready for high traffic.

FAQs

How much RAM do I need for a high-traffic LEMP stack?

We recommend 4GB RAM minimum for production to support performance tuning. Use 8GB+ for very high-traffic environments.

Should I use a static or a dynamic process manager for PHP-FPM?

Use static for maximum speed if you have plenty of RAM; it eliminates startup delays. Use dynamic if RAM is tight, as it saves memory by scaling processes based on demand.

Can I use MySQL instead of MariaDB in LEMP on Linux VPS?

Yes. Simply replace mariadb-server with mysql-server during installation. All configuration and tuning steps in this guide apply to MySQL as well.

Conclusion

You now have a fully optimized LEMP stack running on your Linux VPS, configured specifically for high-traffic scenarios. By tuning Nginx’s worker processes, setting PHP-FPM to static mode, and optimizing MariaDB’s InnoDB settings, your server can handle thousands of concurrent users.

These settings optimize how Nginx handles connections. For static-heavy sites, you should also configure FastCGI caching. You can learn how to set this up in our guide on Advanced Nginx Caching Strategies.

We hope you enjoy this guide on LEMP on Linux VPS. Subscribe to our X and Facebook channels to get the latest updates and articles.

For advanced tuning techniques beyond this standard installation, check out this guide on how to Optimize Nginx and PHP-FPM on VPS.

Post Your Comment

PerLod delivers high-performance hosting with real-time support and unmatched reliability.

Contact us

Payment methods

payment gateway
Perlod Logo
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.