
What We're Building
Before we dive in, let's understand what we're actually building:
- Linux: The operating system (we'll use Ubuntu 22.04 LTS)
- Apache: The web server that serves your website to visitors
- MySQL: The database where your application stores its data
- PHP: The programming language that powers your dynamic content
This combination has been the backbone of the web for decades, and for good reason - it's reliable, well-documented, and works together seamlessly.
Prerequisites: Getting Your VPS Ready
Before we start installing anything, you need:
- A VPS: Any provider will do (DigitalOcean, Vultr, Linode, AWS, etc.)
- Ubuntu 22.04 LTS: Clean installation (most providers offer this as a one-click option)
- SSH Access: Root access or a user with sudo privileges
- Basic Linux Comfort: You don't need to be a sysadmin, but basic command line knowledge helps
Step 1: Initial Server Setup
1.1 Connect to Your Server
First, connect to your VPS via SSH:
ssh root@your_server_ip
1.2 Create a Non-Root User
Never run your server as root. Let's create a user with sudo privileges:
# Create a new user (replace 'youruser' with your preferred username)
adduser youruser
# Add the user to the sudo group
usermod -aG sudo youruser
# Switch to the new user
su - youruser
1.3 Update Your System
This is crucial - always start with an up-to-date system:
sudo apt update
sudo apt upgrade -y
1.4 Configure the Firewall
Ubuntu comes with UFW (Uncomplicated Firewall) which is easy to configure:
# Allow SSH connections first (don't lock yourself out!)
sudo ufw allow OpenSSH
# Enable the firewall
sudo ufw enable
# Check firewall status
sudo ufw status
Step 2: Installing Apache
Apache is the web server component of our stack. It's been around forever (since 1995!) and powers millions of websites.
2.1 Install Apache
sudo apt install apache2 -y
2.2 Start and Enable Apache
sudo systemctl start apache2
sudo systemctl enable apache2
2.3 Verify Apache Installation
Check if Apache is running:
sudo systemctl status apache2
You should see "active (running)" in green. Now, open your web browser and visit your server's IP address. You should see the Apache default page!
2.4 Configure Firewall for Apache
Let's allow web traffic through the firewall:
# Allow HTTP and HTTPS traffic
sudo ufw allow 'Apache Full'
Step 3: Installing MySQL
MySQL is our database server. This is where your application will store all its data - user accounts, blog posts, products, everything.
3.1 Install MySQL Server
sudo apt install mysql-server -y
3.2 Start and Enable MySQL
sudo systemctl start mysql
sudo systemctl enable mysql
3.3 Secure Your MySQL Installation
This is a crucial security step. MySQL comes with a security script that helps you set up important security features:
sudo mysql_secure_installation
You'll be asked several questions:
- Validate Password Component? I recommend saying "yes" - it enforces strong passwords
- Remove Anonymous Users? Definitely say "yes"
- Disallow Remote Root Login? Say "yes" for security
- Remove Test Database? Say "yes" - it's not needed in production
- Reload Privilege Tables? Say "yes" to apply all changes
3.4 Create a Database User
It's better to create a dedicated user for your applications rather than using root:
# Log in to MySQL as root
sudo mysql
# Create a new database user
CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'YourStrongPassword123!';
# Grant the user necessary privileges
GRANT ALL PRIVILEGES ON *.* TO 'appuser'@'localhost' WITH GRANT OPTION;
# Reload privileges and exit
FLUSH PRIVILEGES;
EXIT;
Step 4: Installing PHP
PHP is the programming language that brings your website to life. It processes your code and generates dynamic content.
4.1 Install PHP and Essential Extensions
# Install PHP 8.1 and commonly used extensions
sudo apt install php8.1 php8.1-mysql php8.1-curl php8.1-gd php8.1-mbstring \
php8.1-xml php8.1-zip php8.1-intl php8.1-bcmath php8.1-soap -y
4.2 Configure PHP for Production
PHP needs some configuration tweaks for production use:
sudo nano /etc/php/8.1/apache2/php.ini
Find and adjust these settings:
; Maximum execution time for scripts
max_execution_time = 30
; Maximum amount of memory a script may consume
memory_limit = 256M
; Maximum size of POST data
post_max_size = 64M
; Maximum allowed size for uploaded files
upload_max_filesize = 64M
; Display errors (should be Off in production)
display_errors = Off
; Log errors (should be On in production)
log_errors = On
; Error reporting level
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
4.3 Restart Apache to Load PHP
sudo systemctl restart apache2
Step 5: Testing Your LAMP Stack
Let's make sure everything is working together properly.
5.1 Create a Test PHP File
# Create a test file in Apache's web root
sudo nano /var/www/html/info.php
Add this content:
<?php
phpinfo();
?>
5.2 Test in Browser
Visit http://your_server_ip/info.php
in your browser. You should see the PHP information page showing all your PHP configuration details.
5.3 Remove the Test File (Security!)
Once you've confirmed PHP is working, remove the test file:
sudo rm /var/www/html/info.php
Step 6: Setting Up Virtual Hosts
Virtual hosts allow you to host multiple websites on the same server.
6.1 Create a Directory Structure
# Create directory for your first website
sudo mkdir -p /var/www/yourwebsite.com
# Set proper permissions
sudo chown -R www-data:www-data /var/www/yourwebsite.com
sudo chmod -R 755 /var/www/yourwebsite.com
6.2 Create a Test Web Page
sudo nano /var/www/yourwebsite.com/index.html
Add some basic content:
<!DOCTYPE html>
<html>
<head>
<title>My First LAMP Site</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
.container { max-width: 600px; margin: 0 auto; }
h1 { color: #2c3e50; }
</style>
</head>
<body>
<div class="container">
<h1>🎉 Welcome to Your LAMP Stack!</h1>
<p>Your Ubuntu, Apache, MySQL, and PHP stack is working perfectly!</p>
<p>Current server time: <?php echo date('Y-m-d H:i:s'); ?></p>
</div>
</body>
</html>
6.3 Create Virtual Host Configuration
sudo nano /etc/apache2/sites-available/yourwebsite.com.conf
Add this configuration:
<VirtualHost *:80>
ServerAdmin [email protected]
ServerName yourwebsite.com
ServerAlias www.yourwebsite.com
DocumentRoot /var/www/yourwebsite.com
<Directory /var/www/yourwebsite.com>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/yourwebsite.com_error.log
CustomLog ${APACHE_LOG_DIR}/yourwebsite.com_access.log combined
</VirtualHost>
6.4 Enable Your Virtual Host
# Enable the site
sudo a2ensite yourwebsite.com.conf
# Disable the default Apache site
sudo a2dissite 000-default.conf
# Enable Apache's rewrite module (required for many applications)
sudo a2enmod rewrite
# Test Apache configuration
sudo apache2ctl configtest
# If no errors, restart Apache
sudo systemctl restart apache2
Step 7: Final Security and Optimization
7.1 Install Let's Encrypt for SSL
Every website should use HTTPS. Let's Encrypt provides free SSL certificates:
# Install Certbot
sudo apt install certbot python3-certbot-apache -y
# Get SSL certificate
sudo certbot --apache -d yourwebsite.com -d www.yourwebsite.com
Follow the prompts. Certbot will automatically configure Apache to use HTTPS and set up auto-renewal.
7.2 Optimize MySQL Performance
For a basic VPS, you can optimize MySQL with these settings:
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
Add or adjust these settings:
[mysqld]
innodb_buffer_pool_size = 512M
innodb_log_file_size = 128M
max_connections = 100
query_cache_size = 64M
query_cache_type = 1
sudo systemctl restart mysql
7.3 Set Up Automated Backups
Never skip backups! Here's a simple backup script:
sudo nano /usr/local/bin/backup-lamp.sh
#!/bin/bash
# Backup configuration
BACKUP_DIR="/var/backups/lamp"
DATE=$(date +%Y%m%d_%H%M%S)
MYSQL_USER="appuser"
MYSQL_PASSWORD="YourStrongPassword123!"
# Create backup directory
mkdir -p "$BACKUP_DIR"
# Backup all databases
mysqldump -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" --all-databases > "$BACKUP_DIR/databases_$DATE.sql"
# Backup Apache configuration
tar -czf "$BACKUP_DIR/apache-config_$DATE.tar.gz" /etc/apache2
# Backup PHP configuration
tar -czf "$BACKUP_DIR/php-config_$DATE.tar.gz" /etc/php/8.1
# Compress database backup
gzip "$BACKUP_DIR/databases_$DATE.sql"
# Remove backups older than 7 days
find "$BACKUP_DIR" -name "*.gz" -mtime +7 -delete
echo "Backup completed: $DATE"
sudo chmod +x /usr/local/bin/backup-lamp.sh
# Add to cron for daily backups at 2 AM
echo "0 2 * * * /usr/local/bin/backup-lamp.sh" | sudo crontab -
Common Troubleshooting Issues
Issue 1: Apache Won't Start
Symptoms: Service fails to start, connection refused errors
Solutions:
# Check Apache status for errors
sudo systemctl status apache2
# Check configuration syntax
sudo apache2ctl configtest
# Check error logs
sudo tail -f /var/log/apache2/error.log
# Check if port 80 is being used
sudo netstat -tulpn | grep :80
Issue 2: PHP Files Downloading Instead of Executing
Symptoms: Browser downloads .php files instead of displaying them
Solutions:
# Ensure PHP module is enabled
sudo a2enconf php8.1-fpm
sudo systemctl restart apache2
# Check if libapache2-mod-php is installed
sudo apt install libapache2-mod-php8.1 -y
sudo systemctl restart apache2
Issue 3: MySQL Connection Refused
Symptoms: Database connection errors, "Access denied" messages
Solutions:
# Check MySQL status
sudo systemctl status mysql
# Restart MySQL service
sudo systemctl restart mysql
# Reset MySQL root password (if forgotten)
sudo mysql_secure_installation
# Check MySQL logs
sudo tail -f /var/log/mysql/error.log
Issue 4: 403 Forbidden Errors
Symptoms: Access denied errors, can't view website
Solutions:
# Check file permissions
sudo chown -R www-data:www-data /var/www/yourwebsite.com
sudo chmod -R 755 /var/www/yourwebsite.com
# Check Apache configuration
sudo apache2ctl -S
# Check if .htaccess is causing issues
sudo mv /var/www/yourwebsite.com/.htaccess /var/www/yourwebsite.com/.htaccess.backup
Issue 5: Website is Slow
Symptoms: Long load times, poor performance
Solutions:
# Enable Apache caching
sudo a2enmod cache cache_disk
sudo systemctl restart apache2
# Enable PHP OPcache
sudo nano /etc/php/8.1/apache2/php.ini
# Add: opcache.enable=1
# Check server resources
htop
df -h
free -h
# Optimize MySQL queries
mysql -u appuser -p
# Run: SHOW PROCESSLIST;
What's Next?
Congratulations! You now have a fully functional LAMP stack running on your VPS. Here are some next steps to consider:
- Install a Control Panel: Consider Webmin, ISPConfig, or Virtualmin for easier management
- Set Up Monitoring: Install tools like Uptime Robot or set up basic monitoring scripts
- Configure Email: Set up Postfix or use an external email service
- Install a CMS: WordPress, Drupal, or Joomla run great on LAMP stacks
- Learn Security: Set up fail2ban, configure rate limiting, and implement other security measures
Final Thoughts
Setting up a LAMP stack might seem intimidating at first, but it's a fundamental skill for anyone serious about web development or server administration. The stack we've built today is production-ready and can handle most websites and applications with ease.
Remember, server administration is an ongoing process. Keep your system updated, monitor your logs, and don't be afraid to experiment. Every error message is an opportunity to learn something new.
Happy hosting! 🚀
Got questions or run into issues? Drop them in the comments below - I've probably encountered the same problems and can help you troubleshoot!