Alin Balan
Alin Balan

Software Developer

Verified Expert in Engineering

Full Stack Developer

CTO

Magento Expert

Infrastructure Architect

Blog Post

Installing Magento on Linux: Complete Guide with Redis and Varnish

January 7, 2026 Infrastructure Learning Technology
Installing Magento on Linux: Complete Guide with Redis and Varnish

As a Magento developer and teacher, I often get asked: “How do I set up Magento on a Linux server with proper performance optimizations?” This is a great question because Magento is a powerful e-commerce platform, but it requires careful setup to run efficiently.

In this guide, we’ll walk through installing Magento 2 on a Linux server, along with Redis (for caching) and Varnish (for reverse proxy caching). Don’t worry if you’re still learning—I’ll explain each step and why it matters!

What We’re Building

By the end of this tutorial, you’ll have:

  • Magento 2 installed and running on Linux
  • Redis configured for session and cache storage
  • Varnish configured as a reverse proxy for better performance
  • A production-ready setup that can handle real traffic

Prerequisites

Before we start, make sure you have:

  • A Linux server (Ubuntu 20.04/22.04 or CentOS 7/8 recommended)
  • Root or sudo access
  • At least 2GB RAM (4GB+ recommended)
  • Basic command-line knowledge
  • A domain name or IP address for your store

Understanding the Components

Let’s quickly understand what each piece does:

Magento 2: The e-commerce platform itself—this is where your store lives.

Redis: A fast in-memory database. We’ll use it to:

  • Store session data (so users stay logged in)
  • Cache frequently accessed data (making pages load faster)

Varnish: A reverse proxy that sits in front of Magento. It:

  • Caches full pages for anonymous users
  • Serves cached pages instantly (much faster than Magento)
  • Reduces load on your server

Think of it like this: Varnish is the fast-food drive-through (serves pre-made items quickly), Redis is the kitchen’s prep station (keeps ingredients ready), and Magento is the full kitchen (where everything is prepared).

Step 1: System Preparation

First, let’s update our system and install the basic tools we need.

Update System Packages

# For Ubuntu/Debian
sudo apt update && sudo apt upgrade -y

# For CentOS/RHEL
sudo yum update -y

Install Essential Tools

# Ubuntu/Debian
sudo apt install -y curl wget git unzip software-properties-common

# CentOS/RHEL
sudo yum install -y curl wget git unzip epel-release

Step 2: Install LAMP Stack

Magento needs a web server (Apache/Nginx), PHP, and MySQL/MariaDB. Let’s install the LAMP stack.

Install Apache

# Ubuntu/Debian
sudo apt install -y apache2

# CentOS/RHEL
sudo yum install -y httpd
sudo systemctl enable httpd
sudo systemctl start httpd

Install MySQL/MariaDB

# Ubuntu/Debian
sudo apt install -y mysql-server

# CentOS/RHEL
sudo yum install -y mariadb-server
sudo systemctl enable mariadb
sudo systemctl start mariadb

Secure your MySQL installation:

sudo mysql_secure_installation

You’ll be asked to:

  • Set root password (choose a strong one!)
  • Remove anonymous users (yes)
  • Disallow root login remotely (yes)
  • Remove test database (yes)
  • Reload privilege tables (yes)

Create Magento Database

sudo mysql -u root -p

In the MySQL prompt, run:

CREATE DATABASE magento2 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'magento_user'@'localhost' IDENTIFIED BY 'your_strong_password_here';
GRANT ALL PRIVILEGES ON magento2.* TO 'magento_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Important: Replace your_strong_password_here with a strong password. Write it down—you’ll need it later!

Step 3: Install PHP and Required Extensions

Magento 2 requires PHP 7.4 or higher (PHP 8.1+ recommended). Let’s install PHP 8.1 with all required extensions.

Ubuntu/Debian

# Add PHP repository
sudo add-apt-repository ppa:ondrej/php -y
sudo apt update

# Install PHP 8.1 and extensions
sudo apt install -y php8.1 php8.1-cli php8.1-fpm php8.1-common php8.1-mysql \
    php8.1-zip php8.1-gd php8.1-mbstring php8.1-curl php8.1-xml php8.1-bcmath \
    php8.1-intl php8.1-soap php8.1-redis php8.1-opcache

CentOS/RHEL

# Install Remi repository
sudo yum install -y https://rpms.remirepo.net/enterprise/remi-release-8.rpm

# Enable PHP 8.1
sudo dnf module reset php -y
sudo dnf module enable php:remi-8.1 -y

# Install PHP and extensions
sudo yum install -y php php-cli php-fpm php-common php-mysqlnd \
    php-zip php-gd php-mbstring php-curl php-xml php-bcmath \
    php-intl php-soap php-redis php-opcache

Configure PHP for Magento

Edit the PHP configuration file:

sudo nano /etc/php/8.1/apache2/php.ini  # Ubuntu/Debian
# OR
sudo nano /etc/php.ini  # CentOS/RHEL

Find and update these settings:

memory_limit = 2G
max_execution_time = 1800
zlib.output_compression = On
upload_max_filesize = 64M
post_max_size = 64M
date.timezone = America/New_York  # Change to your timezone

Why these settings?

  • memory_limit: Magento needs plenty of memory for complex operations
  • max_execution_time: Installation and imports can take time
  • upload_max_filesize: For uploading product images
  • date.timezone: Prevents timezone warnings

Step 4: Install Composer

Composer is PHP’s dependency manager. Magento uses it to manage packages.

# Download Composer installer
cd /tmp
curl -sS https://getcomposer.org/installer | php

# Move to global location
sudo mv composer.phar /usr/local/bin/composer
sudo chmod +x /usr/local/bin/composer

# Verify installation
composer --version

Step 5: Install Redis

Redis will handle our caching and sessions. Let’s install and configure it.

Install Redis

# Ubuntu/Debian
sudo apt install -y redis-server

# CentOS/RHEL
sudo yum install -y redis

Configure Redis

Edit the Redis configuration:

sudo nano /etc/redis/redis.conf

Find and update:

maxmemory 256mb
maxmemory-policy allkeys-lru

What this does:

  • maxmemory: Limits Redis to 256MB (adjust based on your server)
  • maxmemory-policy: Removes least recently used keys when memory is full

Start and Enable Redis

sudo systemctl enable redis-server  # Ubuntu/Debian
# OR
sudo systemctl enable redis         # CentOS/RHEL

sudo systemctl start redis-server   # Ubuntu/Debian
# OR
sudo systemctl start redis          # CentOS/RHEL

# Verify it's running
redis-cli ping
# Should return: PONG

Step 6: Install Varnish

Varnish will cache pages and serve them super fast. Let’s install it.

Install Varnish

# Ubuntu/Debian
sudo apt install -y varnish

# CentOS/RHEL
sudo yum install -y varnish

Configure Varnish

Varnish needs to know which port to listen on. By default, it listens on port 6081, but we want it on port 80 (the standard web port).

Edit Varnish configuration:

sudo nano /etc/default/varnish  # Ubuntu/Debian
# OR
sudo nano /etc/varnish/varnish.params  # CentOS/RHEL

For Ubuntu/Debian, find the DAEMON_OPTS section and update:

DAEMON_OPTS="-a :80 \
             -T localhost:6082 \
             -f /etc/varnish/default.vcl \
             -S /etc/varnish/secret \
             -s malloc,256m"

For CentOS/RHEL, update:

VARNISH_LISTEN_PORT=80

Configure Varnish Backend

Edit the Varnish VCL file:

sudo nano /etc/varnish/default.vcl

Replace the backend section with:

backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

This tells Varnish that Apache is running on port 8080 (we’ll configure Apache next).

Configure Apache to Listen on Port 8080

Since Varnish will use port 80, Apache needs to move to port 8080.

sudo nano /etc/apache2/ports.conf  # Ubuntu/Debian
# OR
sudo nano /etc/httpd/conf/httpd.conf  # CentOS/RHEL

Change:

Listen 80

To:

Listen 8080

Also update the virtual host:

sudo nano /etc/apache2/sites-available/000-default.conf  # Ubuntu/Debian
# OR
sudo nano /etc/httpd/conf.d/vhost.conf  # CentOS/RHEL (create if doesn't exist)

Make sure it has:

<VirtualHost *:8080>
    ServerName your-domain.com
    DocumentRoot /var/www/html
    # ... other settings
</VirtualHost>

Start Services

# Restart Apache
sudo systemctl restart apache2  # Ubuntu/Debian
sudo systemctl restart httpd     # CentOS/RHEL

# Start Varnish
sudo systemctl enable varnish
sudo systemctl start varnish

# Check status
sudo systemctl status varnish

Step 7: Download and Install Magento

Now for the main event—installing Magento!

Create Magento Directory

sudo mkdir -p /var/www/html/magento2
sudo chown -R $USER:$USER /var/www/html/magento2
cd /var/www/html/magento2

Download Magento

You have two options:

Option 1: Using Composer (Recommended)

composer create-project --repository-url=https://repo.magento.com/ magento/project-community-edition .

You’ll need Magento authentication keys:

  1. Go to Magento Marketplace
  2. Log in or create an account
  3. Go to “My Access Keys”
  4. Create a new access key
  5. Use the public key as username and private key as password when prompted

Option 2: Download ZIP file

cd /tmp
wget https://github.com/magento/magento2/archive/2.4.6-p1.zip
unzip 2.4.6-p1.zip
sudo mv magento2-2.4.6-p1/* /var/www/html/magento2/

Set Permissions

Magento needs specific permissions:

cd /var/www/html/magento2
sudo find . -type f -exec chmod 644 {} \;
sudo find . -type d -exec chmod 755 {} \;
sudo chmod +x bin/magento
sudo chown -R www-data:www-data .  # Ubuntu/Debian
sudo chown -R apache:apache .       # CentOS/RHEL

Run Magento Installation

Now let’s install Magento using the command line:

cd /var/www/html/magento2
sudo -u www-data php bin/magento setup:install \
    --base-url=http://your-domain.com/ \
    --base-url-secure=https://your-domain.com/ \
    --db-host=localhost \
    --db-name=magento2 \
    --db-user=magento_user \
    --db-password=your_strong_password_here \
    --admin-firstname=Admin \
    --admin-lastname=User \
    --admin-email=[email protected] \
    --admin-user=admin \
    --admin-password=Admin123!@# \
    --language=en_US \
    --currency=USD \
    --timezone=America/New_York \
    --use-rewrites=1 \
    --backend-frontname=admin \
    --session-save=redis \
    --session-save-redis-host=127.0.0.1 \
    --session-save-redis-port=6379 \
    --session-save-redis-db=0 \
    --cache-backend=redis \
    --cache-backend-redis-server=127.0.0.1 \
    --cache-backend-redis-port=6379 \
    --cache-backend-redis-db=1 \
    --page-cache=redis \
    --page-cache-redis-server=127.0.0.1 \
    --page-cache-redis-port=6379 \
    --page-cache-redis-db=2

Breaking down the important parts:

  • --base-url: Your store’s URL
  • --db-*: Database connection details
  • --admin-*: Admin user credentials (change these!)
  • --session-save=redis: Use Redis for sessions
  • --cache-backend=redis: Use Redis for cache
  • --page-cache=redis: Use Redis for page cache

Important:

  • Replace your-domain.com with your actual domain or IP
  • Replace your_strong_password_here with your database password
  • Change the admin password to something secure!

Configure Apache Virtual Host

Create a proper virtual host for Magento:

sudo nano /etc/apache2/sites-available/magento.conf  # Ubuntu/Debian
# OR
sudo nano /etc/httpd/conf.d/magento.conf  # CentOS/RHEL

Add:

<VirtualHost *:8080>
    ServerName your-domain.com
    ServerAlias www.your-domain.com
    DocumentRoot /var/www/html/magento2/pub
    
    <Directory /var/www/html/magento2/pub>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    
    ErrorLog ${APACHE_LOG_DIR}/magento_error.log
    CustomLog ${APACHE_LOG_DIR}/magento_access.log combined
</VirtualHost>

Enable the site and required modules:

# Ubuntu/Debian
sudo a2ensite magento.conf
sudo a2enmod rewrite
sudo systemctl restart apache2

# CentOS/RHEL
sudo systemctl restart httpd

Step 8: Configure Varnish for Magento

Magento needs a special Varnish configuration. Let’s update it:

sudo nano /etc/varnish/default.vcl

Replace the entire file with Magento’s recommended VCL:

vcl 4.0;

import std;
import directors;

backend default {
    .host = "127.0.0.1";
    .port = "8080";
    .first_byte_timeout = 600s;
    .connect_timeout = 600s;
}

acl purge {
    "127.0.0.1";
    "localhost";
}

sub vcl_recv {
    if (req.method == "PURGE") {
        if (client.ip !~ purge) {
            return (synth(405, "Method not allowed"));
        }
        if (!req.http.X-Magento-Tags-Pattern) {
            return (synth(400, "X-Magento-Tags-Pattern header required"));
        }
        ban("obj.http.X-Magento-Tags ~ " + req.http.X-Magento-Tags-Pattern);
        return (synth(200, "Purged"));
    }

    if (req.method != "GET" && req.method != "HEAD" && req.method != "PUT" && 
        req.method != "POST" && req.method != "TRACE" && req.method != "OPTIONS" && 
        req.method != "DELETE") {
        return (pipe);
    }

    if (req.method != "GET" && req.method != "HEAD") {
        return (pass);
    }

    if (req.url ~ "\.(ico|css|js|gif|jpe?g|png|bmp|tiff|svg|swf|flv|mp4|mov|avi|wmv|mp3|wav|pdf|zip|tar|gz|bz2|rar|7z)(\?.*)?$") {
        return (hash);
    }

    if (req.http.Authorization || req.http.Cookie ~ "X-Magento-Vary=") {
        return (pass);
    }

    return (hash);
}

sub vcl_hash {
    if (req.http.cookie ~ "X-Magento-Vary=") {
        hash_data(req.http.X-Magento-Vary);
    }
}

sub vcl_backend_response {
    set beresp.grace = 2m;
    
    if (beresp.status == 200 || beresp.status == 301 || beresp.status == 404) {
        if (beresp.http.Content-Type ~ "text/html" || beresp.http.Content-Type ~ "text/xml") {
            set beresp.ttl = 300s;
            set beresp.do_esi = true;
        } else {
            set beresp.ttl = 86400s;
        }
    } else {
        set beresp.ttl = 0s;
    }
    
    return (deliver);
}

sub vcl_deliver {
    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT";
        set resp.http.X-Cache-Hits = obj.hits;
    } else {
        set resp.http.X-Cache = "MISS";
    }
}

Restart Varnish:

sudo systemctl restart varnish

Step 9: Enable Varnish in Magento

Tell Magento to use Varnish:

cd /var/www/html/magento2
sudo -u www-data php bin/magento config:set --scope=default --scope-code=0 system/full_page_cache/caching_application 2
sudo -u www-data php bin/magento cache:flush

Step 10: Final Configuration

Set Production Mode

For production, set Magento to production mode:

cd /var/www/html/magento2
sudo -u www-data php bin/magento deploy:mode:set production

Generate Static Content

sudo -u www-data php bin/magento setup:static-content:deploy -f

Reindex

sudo -u www-data php bin/magento indexer:reindex

Set Up Cron Jobs

Magento needs cron jobs for various tasks:

sudo crontab -u www-data -e  # Ubuntu/Debian
sudo crontab -u apache -e     # CentOS/RHEL

Add:

* * * * * /usr/bin/php /var/www/html/magento2/bin/magento cron:run | grep -v "Ran jobs by schedule" >> /var/www/html/magento2/var/log/magento.cron.log
* * * * * /usr/bin/php /var/www/html/magento2/bin/magento setup:cron:run >> /var/www/html/magento2/var/log/setup.cron.log

Step 11: Verify Everything Works

Check Services

# Check all services are running
sudo systemctl status apache2   # or httpd
sudo systemctl status redis
sudo systemctl status varnish
sudo systemctl status mysql     # or mariadb

Test Your Store

  1. Open your browser and go to http://your-domain.com
  2. You should see the Magento storefront
  3. Go to http://your-domain.com/admin and log in with your admin credentials

Check Redis is Working

redis-cli
> SELECT 0
> KEYS *
> SELECT 1
> KEYS *
> SELECT 2
> KEYS *
> EXIT

You should see keys in databases 0 (sessions), 1 (cache), and 2 (page cache).

Check Varnish is Caching

curl -I http://your-domain.com

Look for X-Cache: HIT or X-Cache: MISS in the headers. First request should be MISS, second should be HIT.

Troubleshooting Common Issues

Issue: “500 Internal Server Error”

Check:

  1. File permissions: sudo chown -R www-data:www-data /var/www/html/magento2
  2. PHP errors: sudo tail -f /var/log/apache2/error.log
  3. Magento logs: tail -f /var/www/html/magento2/var/log/system.log

Issue: “Redis connection failed”

Check:

  1. Redis is running: sudo systemctl status redis
  2. Redis is listening: redis-cli ping (should return PONG)
  3. PHP Redis extension: php -m | grep redis

Issue: “Varnish not caching”

Check:

  1. Varnish is running: sudo systemctl status varnish
  2. Varnish logs: sudo varnishlog
  3. Magento Varnish config: php bin/magento config:show system/full_page_cache/caching_application

Issue: “Page loads slowly”

Solutions:

  1. Enable all caches: php bin/magento cache:enable
  2. Check Redis memory: redis-cli info memory
  3. Verify Varnish is working: Check for X-Cache: HIT headers

Understanding What We Built

Let’s review what each component does:

  1. Apache (Port 8080): Serves PHP requests and handles Magento
  2. Varnish (Port 80): Caches pages and serves them instantly
  3. Redis: Stores sessions and cache data in memory
  4. MySQL: Stores all your store data (products, orders, etc.)

Request Flow:

  1. User visits your store → Request hits Varnish (port 80)
  2. Varnish checks cache → If cached (HIT), serves immediately
  3. If not cached (MISS) → Varnish forwards to Apache (port 8080)
  4. Apache processes PHP → Magento generates page
  5. Response goes back through Varnish → Varnish caches it
  6. User receives page → Next user gets cached version (super fast!)

Security Considerations

Before going live, consider:

  1. SSL Certificate: Install Let’s Encrypt for HTTPS
  2. Firewall: Configure UFW or firewalld
  3. Admin Path: Change from default /admin to something unique
  4. Two-Factor Authentication: Enable for admin users
  5. Regular Updates: Keep Magento, PHP, and all components updated

Next Steps

Now that you have Magento installed:

  1. Configure Your Store: Set up your store information, currency, shipping, etc.
  2. Add Products: Start adding your products
  3. Install Extensions: Browse the Magento Marketplace
  4. Customize Theme: Make it look like your brand
  5. Set Up Backups: Automate database and file backups
  6. Monitor Performance: Use tools like New Relic or Magento’s built-in profiler

Key Takeaways

  • Redis speeds up your store by caching data in memory
  • Varnish dramatically improves page load times by caching full pages
  • Proper configuration is crucial for performance
  • Production mode should be used for live stores
  • Cron jobs are essential for Magento to function properly

Resources for Further Learning

Conclusion

Congratulations! You’ve successfully installed Magento 2 with Redis and Varnish. This setup will give you a solid foundation for a fast, scalable e-commerce store.

Remember:

  • Always test changes in a development environment first
  • Keep backups before making major changes
  • Monitor your server resources (CPU, memory, disk)
  • Stay updated with security patches

If you run into issues, check the logs first—they usually tell you exactly what’s wrong. And don’t hesitate to ask questions in the Magento community forums!

Happy selling! 🛒

Comments