Running Web Apps on Linux VPS (Complete Setup Guide)

Running Web Apps on Linux VPS (Complete Setup Guide)

Running Web Apps on Linux VPS (Complete Setup Guide) blog

Running web apps Linux VPS gives you ultimate control and expansion opportunities. But it takes a comprehensive understanding of the setup process to ensure better performance.

This step-by-step guide walks you through configuring your web server. It also explains how to secure and manage your hosting environment.

Running web applications on a Linux VPS requires consistent performance and flexible configuration options. The comparison table below highlights VPS hosting providers that support modern web stacks and stable deployments. These environments help ensure your apps run smoothly under varying traffic conditions. Explore our recommended VPS hosting options.

Linux VPS Hosting Providers Optimized for Running Web Applications

ProviderUser RatingRecommended For 
Kamatera Logo4.8ScalabilityVisit Kamatera
4.6AffordabilityVisit Hostinger
4.7DevelopersVisit IONOS

Takeaways
  • A VPS gives you full control and affordable dedicated resources.
  • Protect your virtual server with SSH hardening and UFW firewall.
  • The LAMP stack is always perfect for dynamic PHP applications.
  • Docker containers provide SSL certificates and horizontal scaling.
  • Virtual hosts isolate files in separate directories to run many sites.
  • CI/CD pipelines automatically pull the latest code and restart services.
  • Check database connections and service status to verify installations.

Choosing the Right VPS Hosting Provider

The foundation of your whole deployment depends on choosing a reliable hosting provider. Top options like DigitalOcean and Hetzner offer outstanding features.

Hetzner’s CX22 instances are incredibly cost-effective. They provide 2 vCPU cores and 4GB RAM for about €5.38 ($6.42) per month.

This configuration can manage multiple containerized applications at once. You only need to apply proper resource limits.

In addition, you must have the right operating system. You can get long-term support and active maintenance until 2032 with Ubuntu 22.04 LTS.

This duration ensures the OS is compatible with modern stacks. It will continue to receive critical security patches.

The good thing is that you are spending less on a low-cost VPS. But it delivers the same performance as a dedicated server. You can run multiple containers for small to medium workloads without breaking your budget.

Beyond this, always choose a Linux VPS provider that suits your technical needs and growth plans.

Key Prerequisites for Running Web Apps on Linux VPS

Working directly as the super user can create security risks. You must prepare your environment to prevent vulnerabilities and configuration issues. These prerequisites will help you avoid mistakes when running web apps on Linux VPS.

First, grant a non-root user sudo privileges. You may expose your whole system to attacks if you run services as the root user. A dedicated user account limits access to critical system files. This helps to maintain server integrity.

A secured laptop and server rack, with a locked user account and restricted folders

In addition, Ubuntu systems should already have Uncomplicated Firewall (UFW) installed. Confirm its availability with the command line.

You must also prepare domain management. Point your A-records to the IP Address of your VPS server before installing web applications.

You must do this early because DNS propagation takes time. Run curl http://icanhazip.com from your terminal to verify your public IP address.

Security Essentials: Managing the Root User and UFW

You need solid security to run a Virtual Private Server (VPS) exposed to the internet. Automated bots keep scanning for weaknesses. They constantly probe SSH connections and test default credentials.

Start strengthening your security by configuring UFW. Use sudo ufw to allow specific traffic for SSH (port 22), Apache (port 80), and Apache Secure (port 443).

By default, follow the principle of least privilege by blocking everything else.

Your firewall rules should look like:

sudo ufw allow OpenSSH

sudo ufw allow ‘Apache Full’

sudo ufw enable

After this, harden your SSH connection. Edit /etc/ssh/sshd_config and set PermitRootLogin no to disable root login. Use SSH key authentication instead of passwords to prevent brute-force attacks.

Create your SSH key pair locally. Next, copy the public key to your server. A working key-based access makes password authentication unnecessary.

Get detailed security guidelines for web apps through the OWASP Foundation. This would enable you to understand input validation and session management.

Finally, double-check your SSH configuration before logging out. Use a different terminal window to test your new user’s sudo access. You will need to get console access from your hosting service if it locks you out.

1. Installing and Testing the Apache Web Server

Apache is still one of the most popular web servers around the world. Beginners and experts like its ease and extensive documentation.

A globe covered with Apache flags, surrounded by racks and live dashboards

Ubuntu’s package manager enables quick installation. Execute sudo apt install apache2. The system will handle dependencies. Necessary files will download, and the basic settings configuration will happen automatically.

Check the functionality immediately after installation. Go to your server’s IP address in your web browser. The default Ubuntu Apache page will display, confirming successful installation.

This verification enables you to detect problems quickly. Check your firewall rules and ensure Apache is running if the page doesn’t load.

After installation, Apache automatically starts on boot. This keeps your site accessible after unexpected crashes or server reboots.

You need to be familiar with systemctl commands to manage Apache. Use sudo systemctl status apache2 to check service status.

Run sudo systemctl start apache2 to start the service. Use sudo systemctl restart apache2 to restart after configuration changes.

You should be able to handle advanced configurations with the Apache Software Foundation documentation.

Ultahost

Launch, Scale, and Manage your website with high-performance Web Hosting and VPS.
Visit Site Coupons6

2. Securing Your Web Application with MySQL

Database storage is essential for most dynamic web applications. A robust and reliable option is MySQL. It works for both simple blogs and complex e-commerce platforms.

Install MySQL Server with sudo apt install mysql-server. By default, Ubuntu 22.04 features version 8.0.28. This offers better performance and security features.

Run the security script: sudo mysql_secure_installation immediately after installing it. This tool will guide you through vital hardening steps.

The VALIDATE PASSWORD PLUGIN makes a complex password compulsory. Choose from three policy levels:

  • LOW: Requires a minimum of 8 characters
  • MEDIUM: Requires 8+ characters with numeric, mixed case, and special characters
  • STRONG: Prevents common words through dictionary checks.

A server rack highlights MySQL powering secure database storage

Unauthorized database access easily attacks weak passwords. Choose MEDIUM or STRONG for production environments.

The script also enables you to remove anonymous users. Plus, you can disable remote root login and delete the test database. Get high performance and security by answering “yes” to all these questions.

Verify installation by connecting to MySQL with sudo mysql. Use this interface to create databases and users for your applications. It is advisable to grant the necessary permissions without giving complete control until it is necessary.

The MySQL Documentation should help with troubleshooting and advanced configurations.

3. Setting Up PHP for Dynamic Scripting

Millions of personal blogs and enterprise applications rely on PHP. Proper installation ensures compatibility with your frameworks and libraries.

You need three packages for core installation: sudo apt install php libapache2-mod-php php-mysql. These will install PHP 8.1.2, the Apache module, and MySQL connectivity.

However, most applications require these vital extensions:

  • php-curl: Enables HTTP requests to external APIs.
  • php-mbstring: Handles non-ASCII strings correctly.
  • php-xml: Parses XML documents.
  • php-zip: Manages compressed archives.

Include them with: sudo apt install php-curl php-mbstring php-xml php-zip

Next, restart Apache: sudo systemctl restart apache2. This process loads the new extensions into memory.

Create a test file to verify your installation. Place <?php phpinfo(); ?> in /var/www/html/info.php. Use your web browser to access and see detailed configuration information.

Delete this info.php file after testing. Attackers can exploit the sensitive details it contains.

PHP configuration stays in /etc/php/8.1/apache2/php.ini. Set memory limits, upload sizes, and error reporting based on what your application needs.

The PHP documentation helps upgrade between major versions.

4. Configuring Virtual Hosts on a Single VPS

A server rack visualizes a VPS where each website runs in isolation

You need virtual hosts to run multiple websites on one virtual server. A single VPS gives each website its own directory, logs, and configuration.

This Apache feature separates different domains. But they share the same underlying resources and web server process.

Make a unique directory for each site in /var/www/. For instance: sudo mkdir -p /var/www/example.com/public_html. This keeps files organized, and it also stops you accidentally overwriting something.

Use chown -R $USER:$USER /var/www/example. com for correct file permissions. This would secure and hand ownership over to your user account.

Following that, write a server block configuration file in /etc/apache2/sites-available/example.com.conf. This file tells Apache how to respond to requests for your domain.

A basic configuration looks like:

<VirtualHost *:80>

ServerName example.com

ServerAlias www.example.com

DocumentRoot /var/www/example.com/public_html

ErrorLog ${APACHE_LOG_DIR}/error.log

CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

Use sudo a2ensite example.com.conf to enable your new site. Turn off the default configuration: sudo a2dissite 000-default. conf. To apply the changes, restart Apache.

But you might want to test your configuration first: sudo apache2ctl configtest. This test identifies syntax errors that would stop Apache from starting.

Modern Deployment: Running Web Apps with Docker

Developers now deploy applications differently due to containerization. Docker packages your app with all dependencies. This ensures the same behavior across environments.

Use a multi-stage build for a React application. Start compiling your code with node:20-alpine. This lightweight image has Node.js without unneeded bloat.

A server-room scene shows code being built inside a node 20-alpine container

Copy your source files, install dependencies, and develop the production bundle. Then, serve static files by changing to nginx:1.25.4-alpine-slim. This second stage builds a little final image.

Your Dockerfile might look like:

FROM node:20-alpine AS build

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

RUN npm run build

FROM nginx:1.25.4-alpine-slim

COPY –from=build /app/dist /usr/share/nginx/html

Docker Compose effectively manages many container setups. Use one compose.yaml file to define your frontend, database, and reverse proxy. Everything should start with the following command: docker-compose up -d.

This approach makes deployments simple. Build a new image and restart containers to update your app. There is no need for manual file transfers or configuration changes.

There are thousands of pre-built images on the Docker Hub. Search for official images to avoid exposure from untrusted sources.

Resource limits stop runaway containers from taking up all available memory. Keep each replica under control by setting constraints in your compose file: mem_limit: 512m.

Implementing Traefik for Auto SSL and Load Balancing

Traefik v3.1 automatically manages SSL certificates. It also provides powerful load-balancing capabilities.

Traefik is like a reverse proxy. It sits between the internet and your applications. It uses domain names and paths to route incoming HTTP requests to the correct container.

It features Automatic SSL certificates through Let’s Encrypt. You only need to configure your email address. Traefik will generate, renew, and install certificates.

A miniature sailboat navigates glowing currents while balanced weights and lock symbols surround it

Create entry points for HTTP and HTTPS traffic:

entryPoints:

web:

address: “:80”

websecure:

address: “:443”

Configure automatic HTTPS redirection to ensure encryption for all traffic:

http:

routers:

http-catchall:

rule: hostregexp(`{host:.+}`)

entrypoints:

– web

middlewares:

– redirect-to-https

In addition, Traefik makes dynamic scaling easier. You only have to deploy three replicas of your app. Traefik will automatically distribute requests. Traffic will route to healthy instances for any failed container.

Configure routing by labelling your containers in the compose file:

labels:

– “traefik.enable=true”

– “traefik.http.routers.myapp.rule=Host(`example.com`)”

– “traefik.http.routers.myapp.entrypoints=websecure”

– “traefik.http.routers.myapp.tls.certresolver=letsencrypt”

Traefik Labs can guide you through advanced situations like custom error pages.

Build Your App Now with Hostinger Horizons
Turn your idea into a powerful app in minutes with Hostinger Horizons. No coding, no hassle, just AI-powered building that brings your vision to life.
Visit Hostinger

CI/CD: Automating Your Web App Deployment

A playful workshop scene shows code flowing into an automated pipeline

Automatic deployments save time and reduce human error. GitHub Actions give public repositories free CI/CD. Define your automation pipeline by creating a workflow file in .github/workflows/deploy.yml.

Trigger develops on every push to your main branch. The workflow reviews code and builds your Docker image. Then, it pushes it to GitHub Container Registry.

on:

push:

branches: [main]

Use a personal access token to authenticate with ghcr.io. Secure credentials by storing them as a repository secret.

Next, connect to your VPS server via SSH. Pull the latest image and restart your containers:

ssh user@server “cd /app && docker-compose pull && docker-compose up -d”

This workflow finishes in minutes. Next, commit your code, and your changes will go live within five minutes.

Also, get better version control by tagging releases. Trigger workflows on tag creation to deploy specific versions. Automatic updates make it easier to copy files to your remote server.

Comparative Analysis: LAMP Stack vs. Containerized Stacks

You must consider your application type and team expertise when choosing a deployment approach. The table below compares the LAMP stack against containerized stacks:

AspectLAMP StackDocker + Traefik
Primary TargetDynamic PHP (WordPress, Laravel)Static Apps (React, Vue, APIs)
ComplexityModerate (Manual Config)High (Initial Setup)
SecurityUFW + Manual HardeningAuto SSL + Container Isolation
ScalabilityVertical ScalingHorizontal (Replicas)
Update MethodManual apt updatesAutomated CI/CD Pipelines

The LAMP stack works for PHP applications. Apache and MySQL combine effortlessly with WordPress, Laravel, and similar frameworks. Text files and the command line make configuration easier.

A a glowing oil lamp, stacked metal disks, a gear with flame

However, you need to upgrade to larger VPS instances to expand  LAMP. You must manually configure load balancing across multiple servers to exceed vertical scaling.

In contrast, containerized stacks use horizontal scaling to offer high performance. You can deploy extra replicas when traffic increases. Then, reduce them during quiet periods. Each container runs alone, preventing conflicts.

In addition, the initial setup is more complex with Docker. It requires you to understand images, containers, networks, and volumes. But deployment becomes simple after this configuration.

Beyond this, both stacks have different security models. LAMP depends on UFW and the manual hardening of each service. Containers isolate by default, and Traefik handles SSL automatically.

Easiest Ways to Launch Your Website or Online Store

Website builders make it easier to get online without managing a Linux server. Creating a website with top options like Hostinger or IONOS eases your journey. These platforms manage the server. They also handle security updates and backups.

Dedicated e-commerce platforms and WordPress also work for specific needs. However, getting the right resources for your app means finding the right VPS hosting service.

Choosing the best web hosting is only one part of the journey. You may need to upgrade from shared hosting as your project expands.

Verifying Your Deployment and Testing Database Connections

Verifying each component of your installation completes the process of running web apps Linux VPS.

Create an info.php file in your document root containing <?php phpinfo(); ?>. Go to your web browser to confirm PHP modules loaded correctly. You must delete this file after testing to protect configuration details.

Use a simple PDO script to test database connections. Connect to MySQL and query a test table:

<?php

$pdo = new PDO(‘mysql:host=localhost;dbname=todo_list’, ‘username’, ‘password’);

$stmt = $pdo->query(‘SELECT * FROM tasks’);

while ($row = $stmt->fetch()) {

echo $row[‘task_name’];

}

?>

PHP communicating with MySQL indicates a successful output. Misconfigured credentials or missing extensions will show connection errors.

A terminal command checks connectivity, instantly returning the public IP to confirm the server is visible on the internet.

Use curl http://icanhazip.com to verify your server is visible to the public. It returns your public IP address to verify network connectivity.

Query your domain from different locations to confirm that the DNS records are propagating correctly. Use tools like DNS Checker to see how your A records appear worldwide.

Also, visit your domain in a browser to test HTTPS certificates. Click the security encryption padlock icon to verify certificate details and expiration dates.

Use htop or Docker stats to track resource usage. Always ensure containers stay within their memory and CPU usage limits.

Finally, check /var/log/apache2/access.log for HTTP requests. You can also use Docker logs for containerized applications. 

VPS
Cheap VPS
best option

Conclusion

Running web apps Linux VPS gives you complete control over your hosting environment. You only need a proper setup to ensure security and performance. Start with the basics and test the installation. This flexibility will enable you to identify the different benefits of managed and unmanaged VPS.

Next Steps: What Now?

Follow these steps to run web apps on a Linux VPS:

  1. Prepare the necessary prerequisites.
  2. Manage root user and UFW.
  3. Install and test Apache.
  4. Use MySQL to secure web apps.
  5. Set up PHP and configure virtual hosts.
  6. Run web apps with Docker.
  7. Use Traefik for automatic SSL.
  8. Verify deployment and test database connections.

Frequently Asked Questions

What is the difference between VPS and dedicated server hosting?

A VPS doesn’t own the entire physical machine. However, it provides dedicated resources. With a dedicated server, you have access to the entire physical server.

Do I need to install Nginx or Apache for my web app?

Both setups cope with HTTP requests fine. But Apache supports PHP applications with .htaccess. Nginx stands out for static content and reverse proxying. If you prefer this, use sudo apt install nginx.

Can I run multiple websites on a single VPS?

Yes, you can run multiple websites on one VPS with proper resource management. Each site will have its own directory and configuration file. You just have to setup the virtual hosts in Apache or server blocks for Nginx.

What’s the difference between managed and unmanaged VPS?

A managed VPS offers technical support, automatic updates, and server maintenance. In contrast, you are responsible for configuring and securing an unmanaged VPS.

How do I verify my SSH connection is secure?

Make sure you’re only using SSH keys and have password authentication disabled. Set PermitRootLogin no in /etc/ssh/sshd_config. Use sudo ufw to ensure only the ports you need are open on your firewall. Monitor /var/log/auth. log for strange activity.

What should I do after installing Apache or Nginx?

Open your browser and visit the IP address of the server to ensure it is responding. Create virtual hosts for your domains. Then, enable SSL certificates for HTTPS. Run sudo systemctl status apache2 or sudo systemctl status nginx to see the service status.

How do I connect to my VPS server?

SSH from your terminal: ssh username@your-ip-address. Then, on Windows, use PuTTY or Windows Terminal. You could also FTP your files up. You can also use the emergency web console (if available) from your hosting provider.

How do I check if my web application is using too many resources?

Monitor your system resources through htop or Docker stats. Monitor the memory, CPU, and disk I/O usage. Also, set an alert when it crosses a particular threshold.

Handling Webhook Traffic at Scale in n8n

N8n webhook scaling breaks down faster than you'd expect. When request volumes spike, concurrency pressure builds, and executions start backin...
8 min read
Christi Gorbett
Christi Gorbett
Content Marketing Specialist

Running n8n in Production - Stability Checklist

Getting workflows live is only half the battle. n8n production stability is what keeps your automations running reliably when it actually matt...
8 min read
Christi Gorbett
Christi Gorbett
Content Marketing Specialist

CI/CD Pipelines for Deploying n8n Updates

Manually pushing n8n updates across environments is error-prone and time-consuming. A well-configured n8n CI/CD pipeline changes that. It auto...
8 min read
Christi Gorbett
Christi Gorbett
Content Marketing Specialist

Running n8n with Docker Compose vs Bare-Metal VPS

Choosing between n8n Docker Compose vs bare metal VPS comes down to more than personal preference. It affects how you deploy, scale, and maint...
8 min read
Christi Gorbett
Christi Gorbett
Content Marketing Specialist
Click to go to the top of the page
Go To Top
HostAdvice.com provides professional web hosting reviews fully independent of any other entity. Our reviews are unbiased, honest, and apply the same evaluation standards to all those reviewed. While monetary compensation is received from a few of the companies listed on this site, compensation of services and products have no influence on the direction or conclusions of our reviews. Nor does the compensation influence our rankings for certain host companies. This compensation covers account purchasing costs, testing costs and royalties paid to reviewers.