LEMP Stack Setup
Linux, Nginx, MySQL, PHP-FPM installation and configuration.
Quick Install
sudo apt update
sudo apt install nginx mysql-server php-fpm php-mysql -yStep 1: Install Nginx
# Install
sudo apt install nginx -y
# Start and enable
sudo systemctl start nginx
sudo systemctl enable nginx
# Verify
curl http://localhostStep 2: Install MySQL
# Install
sudo apt install mysql-server -y
# Secure installation
sudo mysql_secure_installation
# Create database and user
sudo mysql << EOF
CREATE DATABASE myapp;
CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'strong_password';
GRANT ALL PRIVILEGES ON myapp.* TO 'appuser'@'localhost';
FLUSH PRIVILEGES;
EOFStep 3: Install PHP-FPM
# Install PHP-FPM with extensions
sudo apt install php-fpm php-mysql php-curl php-gd \
php-mbstring php-xml php-zip -y
# Check version
php -v
# Verify FPM socket
ls /var/run/php/Step 4: Configure Nginx for PHP
sudo nano /etc/nginx/sites-available/mysiteNginx Server Block
server {
listen 80;
server_name mysite.com www.mysite.com;
root /var/www/mysite;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
}# Create directory
sudo mkdir -p /var/www/mysite
sudo chown -R $USER:www-data /var/www/mysite
# Enable site
sudo ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/
sudo rm /etc/nginx/sites-enabled/default
# Test and reload
sudo nginx -t
sudo systemctl reload nginxStep 5: PHP-FPM Configuration
# Edit pool config
sudo nano /etc/php/8.1/fpm/pool.d/www.conf
# Key settings
pm = dynamic
pm.max_children = 10
pm.start_servers = 3
pm.min_spare_servers = 2
pm.max_spare_servers = 5
# Restart
sudo systemctl restart php8.1-fpmStep 6: Test PHP
# Create test file
echo "<?php phpinfo(); ?>" | sudo tee /var/www/mysite/info.php
# Visit http://your-server/info.php
# Remove after testing
sudo rm /var/www/mysite/info.phpSSL with Let's Encrypt
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d mysite.com -d www.mysite.comFirewall
sudo ufw allow 'Nginx Full'Verification
# Check all services
sudo systemctl status nginx
sudo systemctl status php8.1-fpm
sudo systemctl status mysql
# Test config
sudo nginx -t
sudo php-fpm8.1 -t - lemp
- nginx
- mysql
- php
- web server