Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 36 ยท Projects and Practice

Project: A LAMP Stack Environment

Build a complete Linux, Apache, MySQL and PHP development environment with Vagrant: Vagrantfile, provisioning script, synced folder, forwarded port and a test.

In this project you build a development environment for a small PHP application: Ubuntu, Apache, MySQL and PHP, with your code on your own computer and served from the guest. When you finish, a teammate can clone the repository, run vagrant up, and open the site in a browser.

The Vagrantfile and scripts are read-only because Vagrant is not available in your browser; the Ruby stand-ins at the end let you test the template logic. Work through the steps on your own computer with Vagrant and VirtualBox installed.

Goal and layout

Final layout of the repository:

TEXT
lamp-demo/
โ”œโ”€โ”€ Vagrantfile
โ”œโ”€โ”€ provision/
โ”‚   โ”œโ”€โ”€ bootstrap.sh
โ”‚   โ””โ”€โ”€ vhost.conf
โ”œโ”€โ”€ public/
โ”‚   โ”œโ”€โ”€ index.php
โ”‚   โ””โ”€โ”€ health.php
โ”œโ”€โ”€ .gitignore
โ”œโ”€โ”€ .gitattributes
โ””โ”€โ”€ README.md

Requirements:

  1. Ubuntu 22.04 guest with Apache 2.4, PHP and MySQL.
  2. The public/ folder is served as the site root, edited on the host.
  3. The site is reachable at http://localhost:8080.
  4. A app database and user are created; credentials come from environment variables with dev defaults.
  5. Provisioning is idempotent: running it twice changes nothing.
  6. One command resets everything.

Step 1: the Vagrantfile

Ruby
Vagrant.require_version ">= 2.3.0"

DB_NAME = ENV.fetch("DB_NAME", "app")
DB_USER = ENV.fetch("DB_USER", "app")
DB_PASS = ENV.fetch("DB_PASS", "dev-only-password")

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/jammy64"
  config.vm.hostname = "lamp"

  config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"
  config.vm.network "forwarded_port", guest: 3306, host: 13306, host_ip: "127.0.0.1"

  config.vm.synced_folder "./public", "/var/www/app",
    owner: "www-data", group: "www-data"

  config.vm.provider "virtualbox" do |vb|
    vb.name   = "lamp-demo"
    vb.memory = 1536
    vb.cpus   = 2
  end

  config.vm.provision "shell",
    path: "provision/bootstrap.sh",
    env: { "DB_NAME" => DB_NAME, "DB_USER" => DB_USER, "DB_PASS" => DB_PASS }
end

Points worth noticing:

  • host_ip: "127.0.0.1" keeps both forwarded ports reachable only from your own computer, which matters for a database with a development password.
  • The synced folder sets owner and group so Apache can read the files.
  • Secrets arrive through env rather than being pasted into the script.

Step 2: the provisioning script

Terminal
#!/usr/bin/env bash
set -euo pipefail
export DEBIAN_FRONTEND=noninteractive

echo "==> Packages"
apt-get update -qq
apt-get install -y -qq apache2 mysql-server php libapache2-mod-php php-mysql

echo "==> Apache virtual host"
install -m 644 /vagrant/provision/vhost.conf /etc/apache2/sites-available/app.conf
a2dissite 000-default >/dev/null 2>&1 || true
a2ensite app >/dev/null
a2enmod rewrite >/dev/null
systemctl reload apache2

echo "==> MySQL database and user"
mysql -e "CREATE DATABASE IF NOT EXISTS \`${DB_NAME}\` CHARACTER SET utf8mb4;"
mysql -e "CREATE USER IF NOT EXISTS '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASS}';"
mysql -e "GRANT ALL PRIVILEGES ON \`${DB_NAME}\`.* TO '${DB_USER}'@'localhost';"
mysql -e "FLUSH PRIVILEGES;"

echo "==> Done"

Why it is safe to run twice:

  • apt-get install -y skips installed packages.
  • install -m 644 overwrites the config with the same content.
  • CREATE ... IF NOT EXISTS statements do nothing the second time.
  • set -euo pipefail stops at the first failure, so an error is never hidden.

(/vagrant is the default synced folder of the project root; we also mounted public separately. If you disable the default folder, copy the provision folder in another way.)

Step 3: the virtual host

provision/vhost.conf:

APACHE
<VirtualHost *:80>
    ServerName lamp.test
    DocumentRoot /var/www/app

    <Directory /var/www/app>
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/app-error.log
    CustomLog ${APACHE_LOG_DIR}/app-access.log combined
</VirtualHost>

Step 4: a test page

public/health.php reads the database and returns a small JSON status, so you can test the whole stack with one request.

PHP
<?php
header('Content-Type: application/json');

$user = getenv('DB_USER') ?: 'app';
$pass = getenv('DB_PASS') ?: 'dev-only-password';

try {
    $pdo = new PDO('mysql:host=localhost;dbname=app;charset=utf8mb4', $user, $pass);
    $version = $pdo->query('SELECT VERSION()')->fetchColumn();
    echo json_encode(['status' => 'ok', 'php' => PHP_VERSION, 'mysql' => $version]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}

Note that Apache's PHP does not see the provisioning variables, so the defaults in the page and in the Vagrantfile must match. In a real application, use a config file or Apache SetEnv generated at provisioning time.

Step 5: run and verify

TEXT
$ vagrant up
...
==> default: ==> Done
$ curl http://localhost:8080/health.php
{"status":"ok","php":"8.1.2","mysql":"8.0.36-0ubuntu0.22.04.1"}
$ vagrant ssh -c "systemctl is-active apache2 mysql"
active
active

Edit public/index.php on your computer and refresh the browser: the change appears immediately because the folder is synced.

Verify idempotence: vagrant provision should finish with no errors and no changes.

Verify the reset: vagrant destroy -f && vagrant up should recreate an identical environment.

Step 6: harden and share

  • Add .vagrant/ to .gitignore and LF rules to .gitattributes (sharing in Git).
  • Pin the box: config.vm.box_version = "..." (version constraints).
  • Write a README with the commands and versions you tested.
  • Add a trigger that dumps the database before vagrant destroy (triggers).

Stretch goals

  1. Make the PHP version configurable (PHP_VERSION=8.3 vagrant up) by adding the right package source.
  2. Add Xdebug and a forwarded port for your IDE.
  3. Add a second machine for MySQL following multi-machine Vagrantfiles, and bind MySQL to its private address.
  4. Turn the whole thing into a custom box (packaging boxes) and measure the time saved.

A stand-in: render the virtual host and check the script

The template logic is plain text processing, which you can test without Vagrant. This Ruby program renders the virtual host from an ERB template and checks that the provisioning script has the properties promised above (strict mode and idempotent database statements).

Ruby Render config, lint provisioning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The last check fails on purpose, because the script contains a plain CREATE DATABASE other; line. That is exactly the kind of statement that makes a second vagrant provision fail, and a quick check like this catches it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use host_ip: "127.0.0.1" on the forwarded MySQL port?

    Without host_ip the port may be reachable from other machines on your network.
  2. 2. Which statement makes the user-creation step safe to run twice?

    IF NOT EXISTS does nothing when the user already exists, which keeps provisioning idempotent.
  3. 3. Why does the script start with set -euo pipefail?

    Strict mode makes failures visible immediately.
  4. 4. You edit public/index.php on your host. Why does the browser show the change with no extra step?

    The synced folder shares the host directory directly with the guest.

Summary

  • You built a LAMP environment from a Vagrantfile, an idempotent shell provisioner, a virtual host and a health page.
  • Forward ports on 127.0.0.1, pass secrets by environment, and use a synced folder so you edit on the host.
  • Verify idempotence with vagrant provision and reproducibility with vagrant destroy -f && vagrant up.
  • Harden it with Git hygiene, a pinned box and a pre-destroy backup trigger.

Next: Project: a three-tier cluster