Install LEMP Stack on FreeBSD
Install Nginx, MySQL 8.4, PHP 8, PHP-FPM, and phpMyAdmin on FreeBSD with PF firewall rules, Nginx virtual hosts, and a dedicated PHP-FPM pool.
This guide walks through a full LEMP stack setup on FreeBSD using Nginx, MySQL 8.4, PHP 8, PHP-FPM, and phpMyAdmin.
By the end, you will have:
- a sudo-enabled admin user
- an updated FreeBSD base system and packages
- Cloudflare DNS configured
- SSH on a custom port
- PF firewall rules in place
- Nginx, MySQL, PHP, and phpMyAdmin installed
- a dedicated PHP-FPM pool and Nginx virtual host for a site
Create a New User
Skip this step if you already have a working sudo user.
Create a new user:
adduserDuring the prompts:
- choose a username such as
newuser - add the user to the
wheelgroup - set a password
Verify the user is in wheel:
id newuserYou should see wheel in the group list.
Install sudo if needed:
pkg install sudoAllow the wheel group to use sudo:
sudo sed -i '' 's/^# %wheel ALL=(ALL:ALL) ALL/%wheel ALL=(ALL:ALL) ALL/' /usr/local/etc/sudoers
cat /usr/local/etc/sudoers | grep '%wheel ALL=(ALL:ALL) ALL'Switch to the new user and verify sudo works:
su - newuser
sudo whoamiIf the command returns root, sudo is configured correctly.
Upgrade FreeBSD
Check the currently installed version:
uname -arUpdate the base system:
sudo freebsd-update fetch
sudo freebsd-update install
sudo freebsd-update upgrade -r 14.2-RELEASEReplace 14.2-RELEASE with the latest release available from https://www.freebsd.org/.
Update Packages
Update repository metadata and installed packages:
sudo pkg update && sudo pkg upgradeChange DNS to Cloudflare
This step is optional but recommended.
Back up the current resolver config:
sudo cp /etc/resolv.conf /etc/resolv.conf.bakEdit the resolver file:
sudo vim /etc/resolv.confUse Cloudflare DNS:
nameserver 1.1.1.1
nameserver 1.0.0.1
nameserver 2606:4700:4700::1111
nameserver 2606:4700:4700::1001Change the SSH Port
This step is optional but recommended.
Edit the SSH daemon config:
sudo vim /etc/ssh/sshd_configSet a custom port and disable root login:
Port 54445
PermitRootLogin noRestart SSH:
sudo service sshd restartVerify SSH is listening on the new port:
sudo sockstat -4 -6 | grep sshdEnable the PF Firewall
This step is optional but recommended.
Edit the PF config:
sudo vim /etc/pf.confUse rules like these:
# Macros
ext_if = "eth0"
# Options
set skip on lo0
# Default deny all
block all
# Allow SSH
pass in on $ext_if proto tcp to port 54445
# Allow HTTP and HTTPS
pass in on $ext_if proto tcp to port 80
pass in on $ext_if proto tcp to port 443
# Allow outgoing traffic
pass out on $ext_if
# Allow MySQL only on localhost
pass in on lo0 proto tcp from 127.0.0.1 to 127.0.0.1 port 3306
# Block external MySQL access
block in on $ext_if proto tcp to any port 3306Check your interface name with:
ifconfigEnable PF on boot:
sudo sysrc pf_enable="YES"
sudo sysrc pf_rules="/etc/pf.conf"
sudo sysrc pflog_enable="YES"Start PF and verify it:
sudo service pf start
sudo pfctl -sr
sudo pfctl -siReconnect using the custom SSH port:
ssh user@server_ip -p 54445Starting the firewall can drop the current SSH session. Reconnect using the custom port if needed.
Install PHP 8 and PHP-FPM
List available PHP versions:
sudo pkg search php | egrep '^php[0-9]+-[0-9]'Install PHP 8.3 and common extensions:
sudo pkg install php83 php83-extensions php83-mysqli php83-mbstring php83-bcmath php83-zip php83-gd php83-curl php83-xml php83-exif php83-gmpEnable and start PHP-FPM:
sudo sysrc php_fpm_enable=YES
sudo service php_fpm startEdit the default pool config:
sudo vim /usr/local/etc/php-fpm.d/www.confUse:
user = www
group = www
listen = /var/run/php-fpm.sock
listen.owner = www
listen.group = www
listen.mode = 0660Restart PHP-FPM:
sudo service php_fpm restartCreate the main PHP config:
sudo cp /usr/local/etc/php.ini-production /usr/local/etc/php.iniEdit php.ini:
sudo vim /usr/local/etc/php.iniDisable commonly abused functions:
disable_functions = exec,passthru,shell_exec,system,proc_open,popenEnable OPcache:
[opcache]
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.use_cwd=1
opcache.validate_timestamps=1
opcache.revalidate_freq=60
opcache.save_comments=1
opcache.file_cache=/tmp/opcacheRestart PHP-FPM again:
sudo service php_fpm restartGenerate a Self-Signed SSL Certificate
Create a self-signed certificate for local testing or internal use:
sudo openssl req -x509 -newkey rsa:2048 -nodes -keyout /etc/ssl/untrusted/default.key -out /etc/ssl/untrusted/default.crt -days 3650Install Nginx
Install Nginx and enable it at boot:
sudo pkg install nginx
sudo sysrc nginx_enable="YES"Start Nginx:
sudo service nginx start
sudo service nginx statusPrepare the virtual host directories:
sudo mkdir -p /usr/local/etc/nginx/sites-available
sudo mkdir -p /usr/local/etc/nginx/sites-enabledBack up the current config:
sudo cp /usr/local/etc/nginx/nginx.conf /usr/local/etc/nginx/nginx.conf.bakEdit the main config:
sudo vim /usr/local/etc/nginx/nginx.confReplace it with:
user www;
worker_processes auto;
pid /var/run/nginx.pid;
error_log /var/log/nginx/error.log;
events {
worker_connections 1024;
}
http {
sendfile on;
tcp_nopush on;
keepalive_timeout 65;
types_hash_max_size 4096;
types_hash_bucket_size 128;
access_log off;
include /usr/local/etc/nginx/mime.types;
default_type application/octet-stream;
gzip on;
gzip_vary on;
gzip_comp_level 5;
gzip_min_length 512;
gzip_buffers 8 64k;
gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml+rss application/x-font-ttf image/svg+xml font/opentype;
gzip_proxied any;
gzip_disable "msie6";
ssl_session_cache shared:SSL:10m;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers HIGH:!aNULL:!MD5;
proxy_cache_path /var/cache/nginx levels=2 keys_zone=cache:10m inactive=60m max_size=1024m;
proxy_cache_key "$host$request_uri";
proxy_temp_path /var/cache/nginx/temp;
proxy_ignore_headers Expires Cache-Control;
proxy_cache_use_stale error timeout invalid_header http_502;
proxy_cache_valid any 1d;
open_file_cache max=10000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
open_file_cache_errors off;
map $http_cookie $no_cache {
default 0;
~SESS 1;
~wordpress_logged_in 1;
}
include /usr/local/etc/nginx/sites-enabled/*;
}Create the default virtual host:
sudo vim /usr/local/etc/nginx/sites-available/defaultUse:
server {
listen 80 default_server;
listen [::]:80 default_server;
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
http2 on;
server_name _;
ssl_certificate /etc/ssl/untrusted/default.crt;
ssl_certificate_key /etc/ssl/untrusted/default.key;
root /usr/local/www/nginx-dist;
index index.html index.htm index.php;
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
location / {
try_files $uri $uri/ /index.php?$args;
location ~ \.php$ {
root /usr/local/www/nginx-dist;
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
location ~ /\.ht {
deny all;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/www/nginx-dist;
}
}Enable the default site:
sudo ln -s /usr/local/etc/nginx/sites-available/default /usr/local/etc/nginx/sites-enabled/defaultTest and restart Nginx:
sudo nginx -t
sudo service nginx restartOpen the default page:
http://server_ipCreate a temporary PHP test file:
echo "<?php
phpinfo();
?>" | sudo tee /usr/local/www/nginx-dist/test.phpOpen the test page:
http://server_ip/test.phpRemove the test file when finished:
sudo rm /usr/local/www/nginx-dist/test.phpInstall and Configure MySQL 8.4
Install the server and client:
sudo pkg install mysql84-server mysql84-clientEnable and start MySQL:
sudo sysrc mysql_enable=YES
sudo service mysql-server start
sudo service mysql-server statusRun the secure setup:
sudo mysql_secure_installationRecommended answers:
- press
Enterif no root password is set yet - answer
Yto set a root password - choose password validation level
1 (MEDIUM)unless you need something stricter - answer
Yto remove anonymous users - answer
Yto disallow remote root login - answer
Yto remove the test database - answer
Yto reload privilege tables
Create the MySQL config:
sudo vim /usr/local/etc/mysql/my.cnfUse:
[mysqld]
bind-address = 127.0.0.1
innodb_buffer_pool_size = 512M
max_connections = 10Restart MySQL:
sudo service mysql-server restartWatch the error log if needed:
sudo tail -f /var/db/mysql/freebsd.errInstall and Configure phpMyAdmin
Search for available phpMyAdmin packages and install the variant that matches your PHP version:
sudo pkg search phpmyadmin
sudo pkg install phpMyAdmin5-php83-5.2.1_1Create the phpMyAdmin database and control user:
sudo mysql -u root -pRun:
CREATE DATABASE phpmyadmin;
CREATE USER 'pma'@'localhost' IDENTIFIED BY 'strong_password_here';
GRANT SELECT, INSERT, UPDATE, DELETE ON phpmyadmin.* TO 'pma'@'localhost';
FLUSH PRIVILEGES;
exitGenerate a random blowfish secret:
openssl rand -base64 24Copy the sample config and edit it:
sudo cp /usr/local/www/phpMyAdmin/config.sample.inc.php /usr/local/www/phpMyAdmin/config.inc.php
sudo vim /usr/local/www/phpMyAdmin/config.inc.phpSet the blowfish secret:
$cfg['blowfish_secret'] = 'your_code';Hide system databases:
$cfg['Servers'][$i]['hide_db'] = '^information_schema|mysql|phpmyadmin|performance_schema|sys$';Set the control user:
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = 'strong_password_here';Enable phpMyAdmin storage tables:
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma__bookmark';
$cfg['Servers'][$i]['relation'] = 'pma__relation';
$cfg['Servers'][$i]['table_info'] = 'pma__table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma__table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma__pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma__column_info';
$cfg['Servers'][$i]['history'] = 'pma__history';
$cfg['Servers'][$i]['table_uiprefs'] = 'pma__table_uiprefs';
$cfg['Servers'][$i]['tracking'] = 'pma__tracking';
$cfg['Servers'][$i]['userconfig'] = 'pma__userconfig';
$cfg['Servers'][$i]['recent'] = 'pma__recent';
$cfg['Servers'][$i]['favorite'] = 'pma__favorite';
$cfg['Servers'][$i]['users'] = 'pma__users';
$cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
$cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
$cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
$cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
$cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
$cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';Create the phpMyAdmin tables:
sudo mysql -u root -p phpmyadmin < /usr/local/www/phpMyAdmin/sql/create_tables.sqlCreate a password hash:
openssl passwdCreate the Nginx basic auth file:
sudo vim /usr/local/etc/nginx/pma_passUse:
pma:password_hashCreate the phpMyAdmin site config:
sudo vim /usr/local/etc/nginx/sites-available/phpmyadminUse:
server {
listen 80;
listen [::]:80;
listen 443 ssl;
listen [::]:443 ssl;
http2 on;
server_name pma.example.com;
ssl_certificate /etc/ssl/untrusted/default.crt;
ssl_certificate_key /etc/ssl/untrusted/default.key;
access_log off;
error_log /var/log/nginx/pma.example.com.error.log error;
root /usr/local/www/phpMyAdmin;
index index.html index.htm index.php;
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
location / {
try_files $uri $uri/ /index.php?$args;
auth_basic "Admin Login";
auth_basic_user_file /usr/local/etc/nginx/pma_pass;
location ~ \.php$ {
root /usr/local/www/phpMyAdmin;
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
location ~ /\.ht {
deny all;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/www/nginx-dist;
}
}Replace pma.example.com with your actual subdomain.
Enable the site:
sudo ln -s /usr/local/etc/nginx/sites-available/phpmyadmin /usr/local/etc/nginx/sites-enabled/phpmyadminTest and restart Nginx:
sudo nginx -t
sudo service nginx restartCreate a database and user for your application:
sudo mysql -u root -pRun:
CREATE USER 'example_user'@'localhost' IDENTIFIED BY 'password';
CREATE DATABASE example_db;
GRANT ALL PRIVILEGES ON example_db.* TO 'example_user'@'localhost';
FLUSH PRIVILEGES;
exitYou should now be able to sign in to phpMyAdmin at https://pma.example.com.
Create a Dedicated Site User
Create a separate user for the hosted application:
sudo adduserWhen prompted for password-based authentication, choose no if you only want to switch to this user through your admin account.
Prepare the web root:
sudo chmod 711 /home/dolphin
sudo mkdir -p /var/www/dolphin/example.com
sudo chmod 711 /var/www/dolphin
sudo chown root:wheel /var/www
sudo chown -R dolphin:dolphin /var/www/dolphin/example.com
sudo chmod -R 755 /var/www/dolphin/example.comCopy and edit the PHP-FPM pool config:
sudo cp /usr/local/etc/php-fpm.d/www.conf /usr/local/etc/php-fpm.d/dolphin.conf
sudo vim /usr/local/etc/php-fpm.d/dolphin.confUse:
[dolphin]
user = dolphin
group = dolphin
listen = /var/run/php-fpm-dolphin.sock
listen.owner = www
listen.group = www
listen.mode = 0660Restart PHP-FPM:
sudo service php_fpm restartCreate the site virtual host:
sudo vim /usr/local/etc/nginx/sites-available/example.comUse:
server {
listen 80;
listen [::]:80;
listen 443 ssl;
listen [::]:443 ssl;
http2 on;
server_name example.com www.example.com;
ssl_certificate /etc/ssl/untrusted/default.crt;
ssl_certificate_key /etc/ssl/untrusted/default.key;
access_log off;
error_log /var/log/nginx/example.com.error.log error;
root /var/www/dolphin/example.com;
index index.html index.htm index.php;
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
location / {
try_files $uri $uri/ /index.php?$args;
location ~ \.php$ {
root /var/www/dolphin/example.com;
fastcgi_pass unix:/var/run/php-fpm-dolphin.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
location ~ /\.ht {
deny all;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/www/nginx-dist;
}
}Enable the site:
sudo ln -s /usr/local/etc/nginx/sites-available/example.com /usr/local/etc/nginx/sites-enabled/example.comTest and restart Nginx:
sudo nginx -t
sudo service nginx restartInstall WordPress
Switch to the site user:
sudo su - dolphinDownload and extract WordPress:
cd /var/www/dolphin/example.com
curl -O https://wordpress.org/latest.tar.gz
tar -xvzf latest.tar.gz
mv wordpress/* .
rm latest.tar.gz && rm -fr wordpressOpen https://example.com in your browser to continue the WordPress installer.