Configure Apache and PHP-FPM on macOS Catalina

Overview

I finally have Altoplace running on my Pair Networks VPS. Over the last few months, I have experimented with different hosting arrangements and WordPress configurations. Now it’s time to start creating content to see if I can create a viable site. To that end, I want to start by writing about my efforts to create a local website development environment on my Mac. My environment may not be perfect and will change over time, but it’s working for me. As always, I welcome comments. I am not an expert; the purpose of my posts is to describe my experience and what I have learned. Hopefully, you may find something helpful here.

As a foundation, I have chosen Homebrew to install most of the software that I am using. Please go to their site for installation instructions. It’s not the only game in town. Apple does provide a web development environment, but their software may be (slightly) out-of-date or hard to configure. MacPorts is another good option. After trying out both, I had a hard time deciding, but finally chose Homebrew for it’s popularity and ease of use.

Finally, I need to note that this post is a bit long, but I think it’s worth the effort.

Using the Apache Event Module

There are multiple sites that describe how to install Apache and PHP on a Mac using Homebrew. But most of them describe using Apache with the pre-fork Multi-Processing Module (MPM). That’s understandable since Homebrew installs Apache with the pre-fork module active. But in the Linux world, the current, default module is the event module. This allows you to run PHP as a separate process, which is called on as needed. With the pre-fork module, PHP is built in (with mod_php) and is executed all the time even if PHP is not required to fulfill the request.

Running Apache with the pre-fork module is probably just fine while working with a local development environment. But I wanted to learn how to use it with the event module, running PHP as a separate process. By the way, you should check out “macOS 10.15 Catalina Apache Setup: Multiple PHP Versions.” This is one of the best posts that I have seen about setting up a local website development environment. It has inspired much of what I have done to setup my local development environment. It also uses Homebrew to install most of the software.

This post is just about Apache and PHP; I will write separate posts about MySQL and other tools.

Install Apache with the brew command

Let’s get started; the first step is to install Apache, using Homebrew. Please install Homebrew and verify your installation if you haven’t done so.

$ brew doctor
Your system is ready to brew.

$ brew install httpd

$ which -a httpd
/usr/local/bin/httpd
/usr/sbin/httpd

$ httpd -v
Server version: Apache/2.4.43 (Unix)
Server built:   Apr  4 2020 01:58:36

$ httpd -V | grep MPM
Server MPM:     prefork

First, we verified that Homebrew is ready to go. Next, we installed Apache. Finally, we ran a couple of commands to check the installation. Note, use the which command to verify that the Homebrew version of Apache is first in your PATH (you will have to restart your terminal session). The last command shows that Apache was installed with the prefork module enabled.

Great. Now, let’s start it up and test it with Safari:

$ brew services start httpd
==> Successfully started `httpd` (label: homebrew.mxcl.httpd)

Enter this URL in Safari: http://localhost:8080

You should see It Works! in your Safari browser. Note, that you had to specify the non-standard 8080 port number as part of the URL. That’s because Homebrew does not like using sudo, which is required if you want to start up Apache with the standard port 80 configuration. That’s called a privileged port and requires root privileges. In addition to the above test that Apache is running, I like to be able to verify that the http processes are running. It’s nice to check when you start Apache and at various times if you want to check things like start time, elapsed time, and the memory footprint. To that end, I wrote a shell script, which I named a2info:

$ cat ~/bin/a2info
#!/bin/zsh
ps -axo user,pid,start,etime,time,nice,vsz,rss,command |\
  egrep 'PID|httpd' | sed '/grep/d'

$ a2info
USER               PID STARTED     ELAPSED      TIME NI      VSZ    RSS COMMAND
george           27624 11:41AM    01:20:31   0:00.22  0  4441444   4052 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
george           27634 11:41AM    01:20:31   0:00.00  0  4310088    828 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
george           27635 11:41AM    01:20:31   0:00.00  0  4318280    852 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
george           27636 11:41AM    01:20:31   0:00.00  0  4318280    844 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
george           27637 11:41AM    01:20:31   0:00.00  0  4310088    824 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
george           27638 11:41AM    01:20:31   0:00.00  0  4310088    856 /usr/local/opt/httpd/bin/httpd -D FOREGROUND

A couple of notes. You want to make sure that the script is executable, chmod +x ~/bin/a2info, and make sure that your local bin directory is in your PATH:

$ echo $PATH
/Users/george/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/VMware Fusion.app/Contents/Public:/Library/Apple/usr/bin

I like putting my local bin directory at the beginning of my PATH. I am currently using the macOS version of zsh; I defined my PATH in my local .zshrc file:

# Default PATH with VMware Fusion installed ...
PATH=/usr/bin:/bin:/usr/sbin:/sbin:/Applications/VMware\ Fusion.app/Contents/Public:/Library/Apple/usr/bin

# Update PATH for Homebrew ...
PATH=/usr/local/bin:/usr/local/sbin:${PATH}

# Add my local bin ...
PATH=$HOME/bin:${PATH}

As you may have guessed, this is how we stop Apache:

$ brew services stop httpd 
Stopping `httpd`... (might take a while)
==> Successfully stopped `httpd` (label: homebrew.mxcl.httpd)

Switching Apache to the event module and port 80

Using port 80 …

Next, I want to change my Apache configuration to use the event module and port 80. To start and stop Apache when using privilege ports, sudo has to be used. Homebrew is designed to not use sudo. You will see examples of it being used, but in my experience, the brew services … command does not play nicely with sudo. Therefore, I wrote my own shell script to start and stop Apache.

Make sure that you have stopped Apache with the above brew services command. I wrote a shell script called a2ctl to start, stop, or restart Apache:

#!/bin/zsh

# Usage: a2ctl start|stop|restart|info

error_exit()
{
  echo -e "$1" 1>&2
  exit 1
}

# Usage
if [[ ! $# -eq 1 || ! ($1 == "start" || $1 == "stop" || $1 == "restart" || $1 == "info") ]]
then
  error_exit "Usage: a2ctl start|stop|restart|info"
else
  action="$1"
fi

pwait()
{ 
  process=$1
  action=$2
  count=0
  
  if [[ $action == "stop" ]]
  then
    until ! pgrep -q $process || [[ $count -gt 5 ]]
    do
      echo "waiting for $process to stop $count ..."
      sleep 1
      ((count++))
    done 
    if ! pgrep -q $process; then
      echo "$process stopped OK ..."
    else
      error_exit "$process failed to stop"
    fi
  else
    # action is start 
    sleep 1 # give process time to die for configuration file errors ...
    until pgrep -q $process || [[ $count -gt 5 ]]
    do
      echo "waiting for $process to start $count ..."
      sleep 1
      ((count++))
    done
    if pgrep -q $process; then
      echo "$process started OK ..."
    else
      error_exit "$process failed to start"
    fi
  fi
}

a2start()
{
  if pgrep -q httpd; then
    echo "Apache is already started ..."
    exit 0
  fi
  
  if [ ! -f "/usr/local/opt/httpd/homebrew.mxcl.httpd.plist" ]; then
    error_exit "Cannot start Apache -- homebrew.mxcl.httpd.plist is missing ..."
  fi
  
  sudo cp /usr/local/opt/httpd/homebrew.mxcl.httpd.plist /Library/LaunchDaemons/
  if [ "$?" != "0" ]; then
    error_exit "homebrew.mxcl.httpd.plist copy failed ..."
  fi
  
  sudo launchctl load /Library/LaunchDaemons/homebrew.mxcl.httpd.plist > /dev/null 2>&1
  pwait httpd start
}

a2stop()
{
  if ! pgrep -q httpd; then
    echo "Apache is already stopped ..."
    exit 0
  fi
 
  sudo launchctl unload /Library/LaunchDaemons/homebrew.mxcl.httpd.plist > /dev/null 2>&1
  pwait httpd stop

  # Don't start automatically
  sudo rm -f /Library/LaunchDaemons/homebrew.mxcl.httpd.plist
}

a2restart()
{
  # First, stop Apache ...
  if ! pgrep -q httpd; then
    echo "Apache is already stopped, so just start it up ..."
    a2start
    exit 0
  fi

  sudo launchctl unload /Library/LaunchDaemons/homebrew.mxcl.httpd.plist > /dev/null 2>&1
  pwait httpd stop

  # Then, start Apache ...
  sudo launchctl load /Library/LaunchDaemons/homebrew.mxcl.httpd.plist > /dev/null 2>&1
  pwait httpd start
}

a2info()
{
  # Get info about running httpd processes
  ps -axo user,pid,start,etime,time,nice,vsz,rss,command |\
    egrep 'PID|httpd' | sed '/grep/d'
}

case $action in
  "start")
    a2start
    ;;
  "stop")
    a2stop
    ;;
  "restart")
    a2restart
    ;;
  "info")
    a2info
    ;;
  *)
    # Should never happen ...
    error_exit "Invalid action ..."
    ;;
esac

exit 0

As noted by the Usage comment, it is very easy to use. Once started, Apache will start automatically when the macOS system is restarted. If stopped, Apache will not start when the system restarts. If stopped or running, restart will (re)start Apache. I also added the a2info functionality. Now that we have our new Apache start/stop script, lets update our Apache configuration to use port 80:

$ cd /usr/local/etc/httpd

$ mkdir -p ~/orig/usr/local/etc/httpd

$ cp httpd.conf ~/orig/usr/local/etc/httpd

$ vi httpd.conf

$ diff ~/orig/usr/local/etc/httpd/httpd.conf .
52c52
< Listen 8080
---
> Listen 80

$ a2ctl start
Password:
Apache started OK ...

# Now enter: http://localhost

You should see It works! again.

Switching to the event module …

Make the following changes to switch Apache to the event module:

$ cd /usr/local/etc/httpd

$ vi httpd.conf

$ diff ~/orig/usr/local/etc/httpd/httpd.conf .
 o o o
66,67c66,67
< #LoadModule mpm_event_module lib/httpd/modules/mod_mpm_event.so
< LoadModule mpm_prefork_module lib/httpd/modules/mod_mpm_prefork.so
---
> LoadModule mpm_event_module lib/httpd/modules/mod_mpm_event.so
> #LoadModule mpm_prefork_module lib/httpd/modules/mod_mpm_prefork.so
489c489
< #Include /usr/local/etc/httpd/extra/httpd-mpm.conf
---
> Include /usr/local/etc/httpd/extra/httpd-mpm.conf

$ a2ctl restart
Password:
Apache stopped OK ...
Apache started OK ...

$ httpd -V | grep MPM
Server MPM:     event

$ a2info
USER               PID STARTED     ELAPSED      TIME NI      VSZ    RSS COMMAND
root             30794  4:26PM       02:25   0:00.03  0  4438644   4300 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
_www             30805  4:26PM       02:25   0:00.00  0  4314008   1436 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
_www             30806  4:26PM       02:25   0:00.00  0  4314008   1424 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
_www             30807  4:26PM       02:25   0:00.00  0  4314008   1456 /usr/local/opt/httpd/bin/httpd -D FOREGROUND

We commented out the prefork module and uncommitted the event module. Uncommenting the Include httpd-mpm.conf file is optional, but it allows updating the number of httpd event servers, etc. This is the default event MPM configuration defined in this file:

$ cd /usr/local/etc/httpd/extra

$ cat httpd-mpm.conf
 o o o
# event MPM
# StartServers: initial number of server processes to start
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadsPerChild: constant number of worker threads in each server process
# MaxRequestWorkers: maximum number of worker threads
# MaxConnectionsPerChild: maximum number of connections a server process serves
#                         before terminating
<IfModule mpm_event_module>
    StartServers             3
    MinSpareThreads         75
    MaxSpareThreads        250
    ThreadsPerChild         25
    MaxRequestWorkers      400
    MaxConnectionsPerChild   0
</IfModule>
 o o o

Change Document Root to the Local User

Because we are setting up a Development environment (don’t do this on a production system), we will move our Document Root to our local user Sites directory. Make the following changes to httpd.conf (changing user to your local user):

# Set local user ...

193,194c193,194
< User _www
< Group _www
---
> User user
> Group staff

# Update Document Root to point to the local user

248,249c248,249
< DocumentRoot "/usr/local/var/www"
< <Directory "/usr/local/var/www">
---
> DocumentRoot /Users/user/Sites
> <Directory /Users/user/Sites>
269c269
<     AllowOverride None
---
>     AllowOverride All

# Restart apache ...

$ a2ctl restart
Password:
Apache stopped OK ...
Apache started OK ...

By the way, if something doesn’t go right, be sure to check the Apache error log at /usr/local/var/log/httpd/error_log. For the “started OK” case you should see a line that says “resuming normal operations.”

Let’s test our new local user root directory. Create a index.html in your ~/Sites directory and test it in your Safari browser:

$ mkdir -p ~/Sites

$ cd ~/Sites

$ vi index.html

$ cat index.html
<h1>Our Local User Web Root</h1>

# In Safari, enter your localhost URL:
# http://localhost

You should see Our Local User Web Root in your browser (you may need to refresh your browser). If all is good, we can move on to installing and configuring PHP-FPM.

Install and Configure PHP-FPM

I have configured Apache to work with the event module and our local Sites document root. Now let’s make the Apache configuration changes to talk to PHP-FPM. We will enable the mod_proxy_fcgi and mod_proxy modules along with httpd.conf changes to enable FastCGI support. You can read more about how this works at the Apache Module mod_proxy_fcgi website. Finally, I will install and configure PHP-FPM.

Configure Apache to work with PHP-FPM

Edit httpd.conf with your favorite text editor. Make the following changes:

131c131
< #LoadModule proxy_module lib/httpd/modules/mod_proxy.so
---
> LoadModule proxy_module lib/httpd/modules/mod_proxy.so
135c135
< #LoadModule proxy_fcgi_module lib/httpd/modules/mod_proxy_fcgi.so
---
> LoadModule proxy_fcgi_module lib/httpd/modules/mod_proxy_fcgi.so

282c282
<     DirectoryIndex index.html
---
>     DirectoryIndex index.php index.html

# and add this block right after the dir_module block ...

# Run php-fpm via proxy_fcgi
<IfModule proxy_fcgi_module>
    <FilesMatch "\.php$">
        SetHandler "proxy:unix:/usr/local/var/run/php-fpm.sock|fcgi://localhost"
    </FilesMatch>
</IfModule>

Restart Apache with the above changes:

$ a2ctl restart
Password:
Apache stopped OK ...
Apache started OK ...

Check the Apache error log if it doesn’t start up OK. At this point Apache is ready to run PHP. We don’t have to touch it again. We can install PHP, change PHP versions, etc., and Apache will keep talking to the currently running PHP version. So let’s move on to our PHP install.

Setting up PHP-FPM to work with Apache

As of this writing, the newest version of PHP is version 7.4. However, my Pair Networks VPS is still using version 7.3. The following instructions will describe how to install and configure PHP version 7.3 as the default version of PHP. I will also install version 7.4. We could use the brew services command to start and stop the PHP-FPM service. But I opted to write a shell script to start and stop PHP-FPM. I can also easily switch PHP versions with my shell script. I will also update the PHP-FPM configuration file to use a Unix socket to talk to Apache (which is ready to go on the Apache side). The PHP brew installation defaults to using a TCP/IP socket, but the Unix socket approach has less overhead. You can read about what’s the difference between a Unix socket and a TCP/IP socket.

Let’s frist install PHP versions 7.3 and 7.4:

$ brew install php@7.3

$ brew install php

# Set the active version of PHP to version 7.3

$ brew link --force --overwrite php@7.3

# Restart your terminal session ...

$ php -v
PHP 7.3.17 (cli) (built: Apr 29 2020 17:23:10) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.17, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.3.17, Copyright (c) 1999-2018, by Zend Technologies

$ brew services start php@7.3
==> Successfully started `php@7.3` (label: homebrew.mxcl.php@7.3)

The first brew command installed PHP version 7.3 and a bunch of dependencies. The second install command installed the latest production version of PHP, which is currently version 7.4. Finally, the third brew command switched the default version of PHP to version 7.3. Note: Be sure to restart your terminal session after completing the brew link command. Then you can verify your PHP version, and I also showed how to start the PHP-FPM services with the brew services command. For now, stop PHP-FPM with the brew services stop php@7.3 command. We need to update the PHP-FPM configuration file, so that it will be able to talk to Apache.

Starting and Stopping PHP-FPM

You can continue using the brew services command to start and stop PHP-FPM. I prefer having a little more control for starting and stopping, including verifying that PHP-FPM actually did start. I have seen cases where the brew services command will report a successful start, but PHP-FPM actually did not start (or died immediately). I also wanted to implement a convenient way to switch PHP versions. Therefore, I wrote a shell script called p7ctl to start, stop, and restart PHP-FPM. I also included an info action to get information about the running PHP-FPM processes. But before we get into the details about p7ctl, let’s update the PHP-FPM configuration for Apache (and some additional tweaks).

First, change directory to /usr/local/etc/php/7.3/php-fpm.d. The default PHP-FPM configuration is in www.conf. You will want to save a copy of that file in a safe place because it has a lot of useful comments in it, but we are going to filter out all the commented lines and make our Unix proxy changes and point to our local user (which you need to update):

$ pwd
/usr/local/etc/php/7.3/php-fpm.d

$ mkdir -p ~/orig/usr/local/etc/php/7.3/php-fpm.d

$ cp www.conf ~/orig/usr/local/etc/php/7.3/php-fpm.d

# Strip out all the comments ...

$ cat www.conf | egrep -v "^;" | egrep -v "^$" > tmpfile

$ mv tmpfile www.conf

$ cat www.conf
[www]
user = _www
group = _www
listen = 127.0.0.1:9000
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

# Update www.conf to use a Unix socket and our local user ...

$ cat www.conf
[www]
user = user
group = staff
listen = /usr/local/var/run/php-fpm.sock
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

Now we are ready to test that PHP-FPM is working with Apache. You will need to first stop (if not stopped already) and then start PHP-FPM with the brew services command. Next, we will create a simple myinfo.php PHP script to test that everything is working:

$ brew services stop php@7.3 
Stopping `php@7.3`... (might take a while)
==> Successfully stopped `php@7.3` (label: homebrew.mxcl.php@7.3)

$ brew services start php@7.3
==> Successfully started `php@7.3` (label: homebrew.mxcl.php@7.3)

$ cd ~/Sites

$ vi myinfo.php

$ cat myinfo.php
<?php phpinfo();

# Run the PHP info test in Safari:
# http://localhost/myinfo.php

You should see the PHP info screen with lots and lots of information about your running PHP installation. Note that the Server API shows FPM/FastCGI. If all is good, then we are about done with the exception of optionally using my p7ctl PHP control script. Also, don’t forget to make the same www.conf changes for PHP-FPM 7.4.

$ cd ../../7.4/php-fpm.d

$ php -v
PHP 7.3.17 (cli) (built: Apr 29 2020 17:23:10) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.17, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.3.17, Copyright (c) 1999-2018, by Zend Technologies

$ brew unlink php@7.3 && brew link --force --overwrite php@7.4
Unlinking /usr/local/Cellar/php@7.3/7.3.17_1... 25 symlinks removed
Linking /usr/local/Cellar/php/7.4.5_2... 24 symlinks created

$ php -v
PHP 7.4.5 (cli) (built: Apr 23 2020 02:25:56) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.5, Copyright (c), by Zend Technologies

# Update www.conf like we did for version 7.3:

$ cat www.conf
[www]
user = user
group = staff
listen = /usr/local/var/run/php-fpm.sock
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

$ brew services start php@7.4
==> Successfully started `php` (label: homebrew.mxcl.php)

# Again, run the myinfo.php script in Safari:
# http://localhost/myinfo.php

$ brew services stop php@7.4 
Stopping `php`... (might take a while)
==> Successfully stopped `php` (label: homebrew.mxcl.php)

I actually showed how you can manually switch PHP-FPM services. You can actually start different PHP-FPM versions without doing the unlink and link commands. But I prefer keeping the Command Line Version of PHP (php -v) in sync with the PHP-FPM version. Also, I don’t know if there could be other side affects from not unlinking and linking.

Using p7ctl instead of the brew services command

I wrote a shell script, p7ctl, to have a little finer control for stopping and starting PHP-FPM. I can easily use it to switch the running version of PHP-FPM (currently, version 7.3 or 7.4). You simply stop the running version and start the new version. Here is my p7ctl shell script:

#!/bin/zsh

# Usage: p7ctl start [7.3|7.4] -- starts 7.3 or 7.4
#          (defaults to currently linked version)
#        p7ctl restart -- restarts the currently linked version
#        p7ctl stop -- stops the currently linked and running version
#        p7ctl info -- get info about running php-fpm processes
#
#        The start action will unlink the current version and link
#        the requested version if different from the linked version.
#        The restart and stop actions only work with the
#        currently linked version.

error_exit()
{
  echo -e "$1" 1>&2
  exit 1
}

# Get the currently linked PHP version ...
linked="php@$(php -v | grep ^PHP | cut -d' ' -f2 | cut -d'.' -f1,2)"

# Get command parameters ...
if [[ ! $# -ge 1 || ! ($1 == "start" || $1 == "stop" || $1 == "restart" || $1 == "info" ) ]]; then
  error_exit "Usage:\tp7ctl start [7.3|7.4]\n\tp7ctl restart\n\tp7ctl stop\n\tp7ctl info"
else
  action="$1"
  if [[ -z $2 ]]; then
    # Default to the linked version
    version=${linked}
  elif [[ ! ($2 == "7.3" || $2 == "7.4") ]]; then
    error_exit "Version $2 is not supported."
  else
    version="php@$2"
  fi
fi

# plist file name format can change (e.g., php vs php@7.3)
plfile=$(find /usr/local/opt/${linked}/homebrew.mxcl.php*.plist)
if [[ $? -ne 0 ]]; then
  error_exit "Did not find linked ${linked} plist file ..."
fi

pwait()
{
  process=$1
  action=$2
  count=0

  if [[ $action == "stop" ]]
  then
    until ! pgrep -q $process || [[ $count -gt 5 ]]
    do
      echo "waiting for $process to stop $count ..."
      sleep 1
      ((count++))
    done
    if ! pgrep -q $process; then
      echo "$process stopped OK ..."
    else
      error_exit "$process failed to stop"
    fi
  else
    # action is start
    sleep 1 # give process time to die for configuration file errors ...
    until pgrep -q $process || [[ $count -gt 5 ]]
    do
      echo "waiting for $process to start $count ..."
      sleep 1
      ((count++))
    done
    if pgrep -q $process; then
      echo "$process started OK ..."
    else
      error_exit "$process failed to start"
    fi
  fi
}

p7start()
{
  if pgrep -q php-fpm; then
    echo "${linked} is already started."
    exit 0
  fi
 
  if [[ ${linked} != ${version} ]]; then
    brew unlink ${linked} > /dev/null 2>&1 &&
      brew link --force --overwrite ${version} > /dev/null 2>&1
    linked=${version}
    plfile=$(find /usr/local/opt/${linked}/homebrew.mxcl.php*.plist)
    if [[ $? -ne 0 ]]; then
      error_exit "Did not find linked ${linked} plist file ..."
    fi
  fi

  cp ${plfile} ~/Library/LaunchAgents/
  if [[ $? -ne 0 ]]; then
    error_exit "${plfile} copy failed ..."
  fi
  
  launchctl load ~/Library/LaunchAgents/$(basename ${plfile}) > /dev/null 2>&1
  pwait php-fpm start
}

p7stop()
{
  if ! pgrep -q php-fpm; then
    echo "${linked} is already stopped ..."
    exit 0
  fi
 
  launchctl unload ~/Library/LaunchAgents/$(basename ${plfile}) > /dev/null 2>&1
  pwait php-fpm stop

  # Don't start automatically
  rm -f ~/Library/LaunchAgents/$(basename ${plfile})
}

p7restart()
{

  # First, stop PHP ...
  if ! pgrep -q php-fpm; then
    echo "${linked} is already stopped, so just start it up ..."
    # Always restart the linked version
    if [[ ${version} != ${linked} ]]; then
      version=${linked}
    fi
    p7start
    exit 0
  fi

  launchctl unload ~/Library/LaunchAgents/$(basename ${plfile}) > /dev/null 2>&1
  pwait php-fom stop

  # Then, start PHP ...
  launchctl load ~/Library/LaunchAgents/$(basename ${plfile}) > /dev/null 2>&1
  pwait php-fpm start
}

p7info()
{
  ps -axo user,pid,start,etime,time,nice,vsz,rss,command |\
    egrep 'PID|php-fpm' | sed '/grep/d'
}

case $action in
  "start")
    p7start
    ;;
  "stop")
    p7stop
    ;;
  "restart")
    p7restart
    ;;
  "info")
    p7info
    ;;
  *)
    # Should never happen ...
    error_exit "Invalid action ..."
    ;;
esac

exit 0

Here are some examples of how to use it (first, be sure to run brew services stop php@7.3 if you previously started PHP-FPM with the brew services start command):

# The currently linked version of PHP
$ php -v
PHP 7.3.17 (cli) (built: Apr 29 2020 17:23:10) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.17, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.3.17, Copyright (c) 1999-2018, by Zend Technologies

# Start the currently linked version of PHP-FPM
$ p7ctl start
php@7.3 started OK.

# Trying to start again ...
$ p7ctl start
php@7.3 is already started.

# Get info about our running PHP-FPM processes
$ p7ctl info
USER               PID STARTED     ELAPSED      TIME NI      VSZ    RSS COMMAND
george           60042  4:26PM       00:18   0:00.03  0  4740768  13088 /usr/local/opt/php@7.3/sbin/php-fpm --nodaemonize
george           60044  4:26PM       00:18   0:00.00  0  4740512    724 /usr/local/opt/php@7.3/sbin/php-fpm --nodaemonize
george           60045  4:26PM       00:18   0:00.00  0  4749728    708 /usr/local/opt/php@7.3/sbin/php-fpm --nodaemonize

# Stop the running version
$ p7ctl stop
php@7.3 stopped OK.

# Start a different version (and unlink and link)
$ p7ctl start 7.4
php@7.4 started OK.

# Confirm new linked version
$ php -v
PHP 7.4.5 (cli) (built: Apr 23 2020 02:25:56) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.5, Copyright (c), by Zend Technologies

# Get info about our new running PHP-FPM processes
$ p7ctl info     
USER               PID STARTED     ELAPSED      TIME NI      VSZ    RSS COMMAND
george           60408  4:27PM       00:20   0:00.03  0  4872240  13320 /usr/local/opt/php/sbin/php-fpm --nodaemonize
george           60410  4:27PM       00:20   0:00.00  0  4871984    724 /usr/local/opt/php/sbin/php-fpm --nodaemonize
george           60411  4:27PM       00:20   0:00.00  0  4881200    720 /usr/local/opt/php/sbin/php-fpm --nodaemonize

Setting up Virtual Hosts

At this point, Apache and PHP-FPM is working with our Mac localhost. The last item that we want to configure is our virtual hosts environment. We want to be able to create testing host domains that are local to our Mac. For example, I have created a local test domain called altoplace.tst.

For each virtual host, we need a DNS entry, so that we’re able to enter that name into our Safari (or your favorite) browser on your Mac. We could add an entry for each virtual host to our /etc/hosts file, but instead of doing that, we will install a lightweight DNS server on our Mac that will resolve any domain name ending in txt (or test, or whatever local TLD you choose). Of course, don’t pick at real TLD. Also, I understand that the current version of Google Chrome forces all .dev domains to use SSL, so .dev might not be a good choice. We are going to install and use dnsmasq, using Homebrew. Also, I will show you my shell script, dnsctl, that I use to start and stop dnsmasq. Dnsmasq requires root privileges, and as I noted before, the brew services command does not play well with the sudo command.

Using a lightweight DHCP and caching DNS server, dnsmasq

Run the following commands to install and configure dnsmasq:

$ brew install dnsmasq

$ sudo mkdir -p /etc/resolver

$ cd /usr/local/etc

$ mkdir -p ~/orig/usr/local/etc

$ cp dnsmasq.conf ~/orig/usr/local/etc

$ vi dnsmasq.conf

$ diff ~/orig/usr/local/etc/dnsmasq.conf .
79a80
> address=/.tst/127.0.0.1

$ sudo bash -c 'echo "nameserver 127.0.0.1" > /etc/resolver/tst'

The last three lines creates our .tst domain. Actually, I made this a bit more complicated than needed. You could have just created a one line dnsmasq.conf file that contains address=/.tst/127.0.0.1. None of the other configuration options in this file are turned on for our simple application, but I wanted to keep the file as is in case I choose to make other configuration changes in the future.

At this point, we are ready to start the dnsmasq service. However, it needs to be started with root privileges, so I am going to again create my own shell script to start and stop dnsmasq. I called it dnsctl:

#!/bin/zsh

# Usage: dnsctl start|stop|restart|info

error_exit()
{
  echo -e "$1" 1>&2
  exit 1
}

# Usage
if [[ ! $# -eq 1 || ! ($1 == "start" || $1 == "stop" || $1 == "restart" || $1 == "info") ]]
then
  error_exit "Usage: dnsctl start|stop|restart|info"
else
  action="$1"
fi

pwait()
{
  process=$1
  action=$2
  count=0

  if [[ $action == "stop" ]]
  then
    until ! pgrep -q $process || [[ $count -gt 5 ]]
    do
      echo "waiting for $process to stop $count ..."
      sleep 1
      ((count++))
    done
    if ! pgrep -q $process; then
      echo "$process stopped OK ..."
    else
      error_exit "$process failed to stop"
    fi
  else
    # action is start
    sleep 1 # give process time to die for configuration file errors ...
    until pgrep -q $process || [[ $count -gt 5 ]]
    do
      echo "waiting for $process to start $count ..."
      sleep 1
      ((count++))
    done
    if pgrep -q $process; then
      echo "$process started OK ..."
    else
      error_exit "$process failed to start"
    fi
  fi
}

dnsstart()
{
  if pgrep -q dnsmasq; then
    echo "dnsmasq is already started ..."
    exit 0
  fi
  
  if [ ! -f "/usr/local/opt/dnsmasq/homebrew.mxcl.dnsmasq.plist" ]; then
    error_exit "Cannot start dnsmasq -- homebrew.mxcl.dnsmasq.plist is missing ..."
  fi
  
  sudo cp /usr/local/opt/dnsmasq/homebrew.mxcl.dnsmasq.plist /Library/LaunchDaemons/
  if [ "$?" != "0" ]; then
    error_exit "homebrew.mxcl.dnsmasq.plist copy failed ..."
  fi
  
  sudo launchctl load /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist > /dev/null 2>&1
  pwait dnsmasq start
}

dnsstop()
{
  if ! pgrep -q dnsmasq; then
    echo "dnsmasq is already stopped ..."
    exit 0
  fi
 
  sudo launchctl unload /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist > /dev/null 2>&1
  pwait dnsmasq stop

  # Don't start automatically
  sudo rm -f /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist
}

dnsrestart()
{
  # First, stop dnsmasq ...
  if ! pgrep -q dnsmasq; then
    echo "dnsmasq is already stopped, so just start it up ..."
    dnsstart
    exit 0
  fi

  sudo launchctl unload /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist > /dev/null 2>&1
  pwait dnsmasq stop

  # Then, start dnsmasq ...
  sudo launchctl load /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist > /dev/null 2>&1
  pwait dnsmasq start
}

dnsinfo()
{
  # Get info about running dnsmasq processes
  ps -axo user,pid,start,etime,time,nice,vsz,rss,command |\
    egrep 'PID|dnsmasq' | sed '/grep/d'
}

case $action in
  "start")
    dnsstart
    ;;
  "stop")
    dnsstop
    ;;
  "restart")
    dnsrestart
    ;;
  "info")
    dnsinfo
    ;;
  *)
    # Should never happen ...
    error_exit "Invalid action ..."
    ;;
esac

exit 0

The following shows how to start up dnsmasq with the dnsctl shell script:

$ dnsctl
Usage: dnsctl start|stop|restart|info

$ dnsctl start
Password:
dnsmasq started OK ...

$ dnsctl info 
USER               PID STARTED     ELAPSED      TIME NI      VSZ    RSS COMMAND
nobody           37845  3:16PM       00:10   0:00.01  0  4427444   1060 /usr/local/opt/dnsmasq/sbin/dnsmasq --keep-in-foreground -C /usr/local/etc/dnsmasq.conf -7 /usr/local/etc/dnsmasq.d,*.conf

$ ping -c1 anydoman.tst
PING anydoman.tst (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.025 ms

--- anydoman.tst ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.025/0.025/0.025/0.000 ms

Try it out! You can ping any domain that you can dream of (if it ends in .tst). The dnsctl script doesn’t change file permissions like the sudo brew services … command will do (when using sudo). Also, dnsutl tries to verify that the service successfully started (or stopped). I have seen cases where the brew services command said that the service started, but it actually didn’t (or died right away).

Enhanced Dnsmasq Configuration

Updated (6/22/2020): All of the above is still good. However, I learned that there are certain applications, such as the WordPress Site Health check, that do not work with the resolver that we set up at /etc/resolver/tst. The WordPress Site Health check will report critical errors that are failing with this error:

Error: cURL error 6: Could not resolve: yourdomain.tst (Domain name not found) (http_request_failed)

I learned that this error is coming from the brew-installed curl-openssl program. You may not have WordPress installed. Another way to reproduce this issue is with the built-in host command:

$ host anydomain.tst         
Host anydomain.tst not found: 3(NXDOMAIN)

$ ping -c1 anydoman.tst
PING anydoman.tst (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.021 ms

--- anydoman.tst ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.021/0.021/0.021/0.000 ms

The host command fails, but the ping command still works. There is a simple solution. We need to update the MacOS Network DNS setting to add the dnsmasq server IP, which is 127.0.0.1. This can be done through MacOS System Preferences Network panel (click on Advanced... and then the DNS tab). However, we can use the command line to easily change the MacOS DNS setting:

networksetup -setdnsservers Ethernet 127.0.0.1 192.168.1.1
networksetup -setdnsservers Wi-Fi 127.0.0.1 192.168.1.1

A couple of comments. The 127.0.0.1 address must be first. The second address(es) should be a list of your current DNS addresses. You can look at the Network Panel before executing the above commands to determine what those addresses are. If the address is grayed-out, as it was in my case, it means that the DNS address was automatically setup by the DHCP service. You only need to execute the above command for the network interfaces that you are using. In my case, I have setup both Ethernet and Wi-Fi (defaults to using Ethernet).

Now, you can try the same host command and see that the issue is resolved:

$ host anydomain.tst                                        
anydomain.tst has address 127.0.0.1

Also, with this updated configuration, DNS queries are now being cached by dnsmasq:

$ dig +noall +stats altoplace.net
;; Query time: 24 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Mon Jun 22 10:43:38 CDT 2020
;; MSG SIZE  rcvd: 851

$ dig +noall +stats altoplace.net
;; Query time: 0 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Mon Jun 22 10:43:46 CDT 2020
;; MSG SIZE  rcvd: 58

Note that the second Query time is 0 msec. It’s not a big savings, but I guess that it might add up over time. Anyway, the critical WordPress Site Health check issues are resolved. And a final note, if you do make this network DNS update, the /etc/resolver/tst file is no longer needed and can be safely removed.

Creating our First Virtual Host

We first need to make some additional changes to our Apache configuration file and restart Apache:

$ cd /usr/local/etc/httpd

$ vi httpd.conf

$ diff ~/orig/usr/local/etc/httpd/httpd.conf .
 o o o
175c175
< #LoadModule vhost_alias_module lib/httpd/modules/mod_vhost_alias.so
---
> LoadModule vhost_alias_module lib/httpd/modules/mod_vhost_alias.so
182c182
< #LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so
---
> LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so
 o o o
507c514
< #Include /usr/local/etc/httpd/extra/httpd-vhosts.conf
---
> Include /usr/local/etc/httpd/extra/httpd-vhosts.conf

The above configuration changes enable the vhosts module and, while we were at it, the rewrite module. Now, we can add our virtual hosts to httpd-vhosts.conf:

$ cd /usr/local/etc/httpd/extra

$ vi httpd-vhosts.conf

# Delete the example virtual hosts and add:

<VirtualHost *:80>
    DocumentRoot "/Users/george/Sites"
    ServerName localhost
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/Users/george/Sites/altoplace.tst"
    ServerName altoplace.tst
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/Users/george/Sites"
    ServerName imac1.local
</VirtualHost>

# Check you configuration changes:

$ apachectl configtest 
Syntax OK

# Restart Apache
# a2ctl may prompt for your system password depending on the
# last time you used sudo ...

$ a2ctl restart
httpd stopped OK ...
httpd started OK ...

Let me try to explain my changes. Since we turned on virtual hosts, I added our top-level ~/Sites directory as a virtual host. I defined my new altoplace.tst virtual host. And I added a special virtual host, imac1.local, to my vhosts file. The imac1.local domain is my Mac domain that is reachable from any system on my local network. It also points to my top-level ~/Sites directory. You can now add an index.html file and a info.php file to your new vhost directory (e.g., ~/Sites/altoplace.tst) and test that your new Virtual Host is working (http://altoplace.tst).

Setting up SSL (TLS)

SSL is the last topic that I am going to discuss in this post. It adds the ability to test SSL enabled virtual hosts (e.g., https://altoplace.tst). This is an important topic since the use of SSL is highly encouraged and is inexpensive to do. These days, you will see a new term, TLS, replacing SSL. You can read about SSL/TLS at the SSL link that I just provided. They are both protocols for establishing authenticated and encrypted links between networked computers.

Updating httpd.conf and extra/httpd-ssl.conf to support SSL

We just need to make a few more changes to our Apache httpd.conf and extra/httpd-ssl.conf configuration files to support the use of SSL:

# Update httpd.conf ...

$ diff ~/orig/usr/local/etc/httpd/httpd.conf .
 o o o
92c92
< #LoadModule socache_shmcb_module lib/httpd/modules/mod_socache_shmcb.so
---
> LoadModule socache_shmcb_module lib/httpd/modules/mod_socache_shmcb.so
 o o o
150c150
< #LoadModule ssl_module lib/httpd/modules/mod_ssl.so
---
> LoadModule ssl_module lib/httpd/modules/mod_ssl.so
 o o o
524c531
< #Include /usr/local/etc/httpd/extra/httpd-ssl.conf
---
> Include /usr/local/etc/httpd/extra/httpd-ssl.conf

# Update extra/httpd-ssl.conf ...

$ cd /usr/local/etc/httpd/extra               

$ cp httpd-ssl.conf ~/orig/usr/local/etc/httpd/extra

$ vi httpd-ssl.conf

$ diff ~/orig/usr/local/etc/httpd/extra/httpd-ssl.conf .
36c36
< Listen 8443
---
> Listen 443
121c121
< <VirtualHost _default_:8443>
---
> <VirtualHost _default_:443>
124,125c124,125
< DocumentRoot "/usr/local/var/www"
< ServerName www.example.com:8443
---
> #DocumentRoot "/usr/local/var/www"
> #ServerName www.example.com:8443
144c144
< SSLCertificateFile "/usr/local/etc/httpd/server.crt"
---
> SSLCertificateFile "/usr/local/etc/httpd/ssl/localhost+2.pem"
154c154
< SSLCertificateKeyFile "/usr/local/etc/httpd/server.key"
---
> SSLCertificateKeyFile "/usr/local/etc/httpd/ssl/localhost+2-key.pem"

We just uncommented two LoadModule lines to enable SSL. We also uncommented and updated the httpd-ssl.conf include file (don’t try to restart Apache yet). We changed the Homebrew defined SSL port number (8443) back to the default SSL port number (443). We still need to create the SSL certificate and key files before restarting Apache.

Updating our Virtual Hosts to use SSL

We need to update our Virtual Hosts configuration to add SSL-enabled virtual hosts to our Apache configuration:

$ cd /usr/local/etc/httpd/extra

$ vi httpd-vhosts.conf

# Add the following ...

<VirtualHost *:443>
    DocumentRoot "/Users/george/Sites"
    ServerName localhost
    SSLEngine on
    SSLCertificateFile "/usr/local/etc/httpd/ssl/localhost+2.pem"
    SSLCertificateKeyFile "/usr/local/etc/httpd/ssl/localhost+2-key.pem"
</VirtualHost>

<VirtualHost *:443>
    DocumentRoot "/Users/george/Sites"
    ServerName imac1.local
    SSLEngine on
    SSLCertificateFile "/usr/local/etc/httpd/ssl/imac1.local.pem"
    SSLCertificateKeyFile "/usr/local/etc/httpd/ssl/imac1.local-key.pem"
</VirtualHost>

<VirtualHost *:443>
    DocumentRoot "/Users/george/Sites/altoplace.tst"
    ServerName altoplace.tst
    SSLEngine on
    SSLCertificateFile "/usr/local/etc/httpd/ssl/altoplace.tst.pem"
    SSLCertificateKeyFile "/usr/local/etc/httpd/ssl/altoplace.tst-key.pem"
</VirtualHost>

Again, we still are not ready to restart Apache. We will now create the local SSL certificate and key files referenced in the httpd-vhosts.conf and extra/httpd-ssl.conf files.

Creating the local SSL certificates and keys

We could use OpenSSL to create a self-signed certificate. But instead, we are going to use mkcert to create our SSL certificates. It is very easy to use to create locally trusted development certificates. We can use Homebrew to install mkcert. Here’s how to install and use mkcert:

$ brew install mkcert nss

$ mkcert -install
Created a new local CA at "/Users/george/Library/Application Support/mkcert" ?
The local CA is now installed in the system trust store! ⚡️

$ cd /usr/local/etc/httpd

$ mkdir ssl

$ cd ssl

$ mkcert localhost 127.0.0.1 ::1
Using the local CA at "/Users/george/Library/Application Support/mkcert" ✨

Created a new certificate valid for the following names ?
 - "localhost"
 - "127.0.0.1"
 - "::1"

The certificate is at "./localhost+2.pem" and the key at "./localhost+2-key.pem" ✅

$ mkcert altoplace.tst
Using the local CA at "/Users/george/Library/Application Support/mkcert" ✨

Created a new certificate valid for the following names ?
 - "altoplace.tst"

The certificate is at "./altoplace.tst.pem" and the key at "./altoplace.tst-key.pem" ✅

$ mkcert imac1.local
Using the local CA at "/Users/george/Library/Application Support/mkcert" ✨

Created a new certificate valid for the following names ?
 - "imac1.local"

The certificate is at "./imac1.local.pem" and the key at "./imac1.local-key.pem" ✅

The nss formal provides libraries that Firefox needs for using SSL. We ran mkcert -install one time to install a locally trusted certificate in our system trust store. Then we created a certificate for localhost. The last two examples shows how easy it is to create additional certificates for locally hosted domains. Of course, you will use your own local development domains. At this point, you are ready to restart Apache and test your newly SSL-enabled domains. I would suggest running the Apache configuration test first just to verify that you didn’t make any configuration errors. I certainly did find errors the first time around:

$ apachectl configtest                                  
Syntax OK

$ a2ctl restart
Password:
httpd stopped OK ...
httpd started OK ...

$ a2ctl info   
USER               PID STARTED     ELAPSED      TIME NI      VSZ    RSS COMMAND
root             40832  9:39AM       00:36   0:00.03  0  4443360   5100 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
george           40834  9:39AM       00:36   0:00.00  0  4344324   1616 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
george           40835  9:39AM       00:36   0:00.00  0  4326916   1604 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
george           40836  9:39AM       00:36   0:00.00  0  4327940   1560 /usr/local/opt/httpd/bin/httpd -D FOREGROUND

# Now test your SSL URLs:

# https://localhost
# https://imac1.local
# https://altoplace.tst

We ran the Apache configuration test, restarted Apache, and for good measure, we verified that our httpd processes were running (and had just started). If you encounter any errors, be sure to check your Apache error log (/usr/local/var/log/httpd/error_log).

Conclusion

At this point, you should have a basic Apache/PHP-FPM working environment, supporting SSL-enabled virtual hosts. You can start testing website environments, such as Grav, that don’t require a MySQL database. I will write a different post about setting up MySQL to complete our local development LAMP stack (but for the Mac instead of Linux) environment. Then I will write about how I installed WordPress using WP-CLI. All coming later. Please stay tuned …

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.