One place for hosting & domains


      How To Configure Apache HTTP with MPM Event and PHP-FPM on FreeBSD 12.0

      The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.


      The Apache HTTP web server has evolved through the years to work in different environments and solve different needs. One important problem Apache HTTP has to solve, like any web server, is how to handle different processes to serve an http protocol request. This involves opening a socket, processing the request, keeping the connection open for a certain period, handling new events occurring through that connection, and returning the content produced by a program made in a particular language (such as PHP, Perl, or Python). These tasks are performed and controlled by a Multi-Processing Module (MPM).

      Apache HTTP comes with three different MPM:

      • Pre-fork: A new process is created for each incoming connection reaching the server. Each process is isolated from the others, so no memory is shared between them, even if they are performing identical calls at some point in their execution. This is a safe way to run applications linked to libraries that do not support threading—typically older applications or libraries.
      • Worker: A parent process is responsible for launching a pool of child processes, some of which are listening for new incoming connections, and others are serving the requested content. Each process is threaded (a single thread can handle one connection) so one process can handle several requests concurrently. This method of treating connections encourages better resource utilization, while still maintaining stability. This is a result of the pool of available processes, which often has free available threads ready to immediately serve new connections.
      • Event: Based on worker, this MPM goes one step further by optimizing how the parent process schedules tasks to the child processes and the threads associated to those. A connection stays open for 5 seconds by default and closes if no new event happens; this is the keep-alive directive default value, which retains the thread associated to it. The Event MPM enables the process to manage threads so that some threads are free to handle new incoming connections while others are kept bound to the live connections. Allowing re-distribution of assigned tasks to threads will make for better resource utilization and performance.

      The MPM Event module is a fast multi-processing module available on the Apache HTTP web server.

      PHP-FPM is the FastCGI Process Manager for PHP. The FastCGI protocol is based on the Common Gateway Interface (CGI), a protocol that sits between applications and web servers like Apache HTTP. This allows developers to write applications separately from the behavior of web servers. Programs run their processes independently and pass their product to the web server through this protocol. Each new connection in need of processing by an application will create a new process.

      By combining the MPM Event in Apache HTTP with the PHP FastCGI Process Manager (PHP-FPM) a website can load faster and handle more concurrent connections while using fewer resources.

      In this tutorial you will improve the performance of the FAMP stack by changing the default multi-processing module from pre-fork to event and by using the PHP-FPM process manager to handle PHP code instead of the classic mod_php in Apache HTTP.


      Before you begin this guide you’ll need the following:

      • A FreeBSD 12.0 server set up following this guide.
      • The FAMP stack installed on your server following this tutorial.
      • Access to a user with root privileges (or allowed by using sudo) in order to make configuration changes.

      Step 1 — Changing the Multi-Processing Module

      You’ll begin by looking for the pre-fork directive in the httpd.conf file. This is the main configuration file for Apache HTTP in which you can enable and disable modules. You can edit and set directives such as the listening port where Apache HTTP will serve content or the location of the content to display in this file.

      To make these changes, you’ll use the nl, number line, program, with the -ba flag to count and number lines so that nothing is mismatched at a later stage. Combined with grep this command will first count all the lines in the file specified in the path, and once finished, it will search for the string of characters you’re looking for.

      Run the following command so that the nl program will process and number the lines in httpd.conf. Then, grep will process the output by searching for the given string of characters 'mod_mpm_prefork':

      • nl -ba /usr/local/etc/apache24/httpd.conf | grep 'mod_mpm_prefork'

      As output you’ll see something similar to:


      67 LoadModule mpm_prefork_module libexec/apache24/

      Let’s edit line 67 with your text editor. In this tutorial, you’ll use vi, which is the default editor on FreeBSD:

      • sudo vi +67 /usr/local/etc/apache24/httpd.conf

      Append a # symbol at the beginning of the line so this line is commented out, like so:


      # LoadModule mpm_prefork_module libexec/apache24/

      By appending the # symbol you’ve disabled the pre-fork MPM module.

      Now you’ll find the event directive in the same httpd.conf file.

      • nl -ba /usr/local/etc/apache24/httpd.conf | grep mpm_event

      You’ll see output similar to the following:


      ... 66 #LoadModule mpm_event_module libexec/apache24/ ...

      Now you’ll remove the # symbol in line 66 to enable the Event MPM:

      • sudo vi +66 /usr/local/etc/apache24/httpd.conf

      The directive will now read as follows:


      LoadModule mpm_event_module libexec/apache24/

      Now that you’ve switched the configuration from the MPM pre-fork to event, you can remove the mod_php73 package connecting the PHP processor to Apache HTTP, since it is no longer necessary and will interfere if it remains on the system:

      • sudo pkg remove -y mod_php73

      Make sure the configuration is correct by running the following command to test:

      • sudo apachectl configtest

      If you see Syntax OK in your output, you can restart the Apache HTTP server:

      Note: If there are other running HTTP connections on your server a graceful restart is recommended instead of a regular restart. This will ensure that users are not pushed out, losing their connection:

      You've switched the MPM from pre-fork to event and removed the mod_php73 module connection PHP to Apache HTTP. In the next step you'll install the PHP-FPM module and configure Apache HTTP so that it can communicate with PHP more quickly.

      Step 2 — Configuring Apache HTTP to Use the FastCGI Process Manager

      FreeBSD has several supported versions of PHP that you can install via the package manager. On FreeBSD different binaries of the various available versions are compiled instead of using just one like most GNU/Linux distributions offer in their default repositories. To follow best practice you'll use the supported version, which you can check on at PHP's supported versions page.

      In this step you'll add PHP-FPM as a running service to start at boot. You'll also configure Apache HTTP to work with PHP by adding a dedicated configuration for the module as well as enabling some further modules in httpd.conf.

      First you'll append 'php_fpm_enable=YES' to the /etc/rc.conf file so the PHP-FPM service can start. You'll do that by using the sysrc command:

      • sudo sysrc php_fpm_enable="YES"

      Now you'll add the php-fpm module into the Apache module's directory, so it is configured to be used by Apache HTTP. Create the following file to do so:

      • sudo vi /usr/local/etc/apache24/modules.d/030_php-fpm.conf

      Add the following into 030_php-fpm.conf:


      <IfModule proxy_fcgi_module>
          <IfModule dir_module>
              DirectoryIndex index.php
          <FilesMatch ".(php|phtml|inc)$">
              SetHandler "proxy:fcgi://"

      This states that if the module 'proxy_fcgi' is enabled as well as the 'dir_module' then any processed files matching the extensions in parentheses should be handled by the FastCGI process manager running on the local machine through port 9000—as if the local machine were a proxy server. This is where the PHP-FPM module and Apache HTTP interconnect. To achieve this, you'll activate further modules during this step.

      To enable the proxy module, you'll first search for it in the httpd.conf file:

      • nl -ba /usr/local/etc/apache24/httpd.conf | grep

      You'll see output similar to the following:


      ... 129 #LoadModule proxy_module libexec/apache24/ ...

      You'll uncomment the line by removing the # symbol:

      • sudo vi +129 /usr/local/etc/apache24/httpd.conf

      The line will look as follows once edited:


      LoadModule proxy_module libexec/apache24/

      Now you can activate the FastCGI module. Find the module with the following command:

      • nl -ba /usr/local/etc/apache24/httpd.conf | grep

      You'll see something similar to the following:


      ... 133 #LoadModule proxy_fcgi_module libexec/apache24/ ...

      Now uncomment the line 133 as you've already done with the other modules:

      • sudo vi +133 /usr/local/etc/apache24/httpd.conf

      You'll leave the line as follows:


      LoadModule proxy_fcgi_module libexec/apache24/

      Once this is done you'll start the PHP-FPM service:

      • sudo service php-fpm start

      And you'll restart Apache so it loads the latest configuration changes incorporating the PHP module:

      You've installed the PHP-FPM module, configured Apache HTTP to work with it, enabled the necessary modules for the FastCGI protocol to work, and started the corresponding services.

      Now that Apache has the Event MPM module enabled and PHP-FPM is present and running, it is time to check everything is working as intended.

      Step 3 — Checking Your Configuration

      In order to check that the configuration changes have been applied you'll run some tests. The first one will check what multi-processing module Apache HTTP is using. The second will verify that PHP is using the FPM manager.

      Check the Apache HTTP server by running the following command:

      • sudo apachectl -M | grep 'mpm'

      Your output will be as follows:


      mpm_event_module (shared)

      You can repeat the same for the proxy module and FastCGI:

      • sudo apachectl -M | grep 'proxy'

      The output will show:


      proxy_module (shared) proxy_fcgi_module (shared)

      If you would like to see the entire list of the modules, you can remove the the second part of the command after -M.

      It is now time to check if PHP is using the FastCGI Process Manager. To do so you'll write a very small PHP script that will show you all the information related to PHP.

      Run the following command to write a file named as follows:

      • sudo vi /usr/local/www/apache24/data/info.php

      Add the following content into the info.php file:


      <?php phpinfo(); ?>

      Now visit your server's URL and append info.php at the end like so: http://your_server_IP_address/info.php.

      The Server API entry will be FPM/FastCGI.

      PHP Screen the Server API entry FPM/FastCGI

      Remember to delete the info.php file after this check so no information about the server is publicly disclosed.

      • sudo rm /usr/local/www/apache24/data/info.php

      You've checked the working status of the MPM module, the modules handling the FastCGI, and the handling of PHP code.


      You've optimized your original FAMP stack, so the number of connections to create new Apache HTTP processes has increased, PHP-FPM will handle PHP code more efficiently, and overall resource utilization has improved.

      See the Apache HTTP server project documentation for more information on the different modules and related projects.

      Source link

      How To Install an Apache, MySQL, and PHP (FAMP) Stack on FreeBSD 12.0

      The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.


      A FAMP stack, which is similar to a LAMP stack on Linux, is a group of open source software that is typically installed together to enable a FreeBSD server to host dynamic websites and web apps. FAMP is an acronym that stands for FreeBSD (operating system), Apache (web server), MySQL (database server), and PHP (to process dynamic PHP content).

      In this guide, we’ll get a FAMP stack installed on a FreeBSD 12.0 cloud server using pkg, the FreeBSD package manager.


      Before you begin this guide you’ll need the following:

      • A FreeBSD 12.0 Droplet.
      • Access to a user with root privileges (or allowed by using sudo) in order to make configuration changes.
      • A firewall configured using this tutorial on Recommended Steps For New FreeBSD 12.0 Servers. Ensure you open ports 80 and 443 as part of your setup.
      • Familiarity with the CLI (Command Line Interface) is recommended. FreeBSD’s vi editor has almost identical syntax as vim.

      Step 1 — Installing Apache

      The Apache web server is currently the most popular web server in the world, which makes it a great choice for hosting a website.

      You can install Apache using FreeBSD’s package manager, pkg. A package manager allows you to install most software pain-free from a repository maintained by FreeBSD. You can learn more about how to use pkg here.

      To install Apache 2.4 using pkg, use this command:

      • sudo pkg install apache24

      Enter y at the confirmation prompt to install Apache and its dependencies.

      To enable Apache as a service, add apache24_enable="YES" to the /etc/rc.conf file. You’ll use the sysrc command to do just that:

      • sudo sysrc apache24_enable="YES"

      Now start Apache:

      • sudo service apache24 start

      To check that Apache has started you can run the following command:

      • sudo service apache24 status

      As a result you’ll see something similar to:


      apache24 is running as pid 20815.

      You can do a spot check right away to verify that everything went as planned by visiting your server’s public IP address in your web browser. See the note under the next heading to find out what your public IP address is, if you do not have this information already:


      You will see the default FreeBSD Apache web page, which is there for testing purposes. You’ll see: It Works!, which indicates that your web server is correctly installed.

      How To find Your Server’s Public IP Address

      If you do not know what your server’s public IP address is, there are a number of ways that you can find it. Usually, this is the address you use to connect to your server through SSH.

      If you are using DigitalOcean, you may look in the Control Panel for your server’s IP address. You may also use the DigitalOcean Metadata service, from the server itself, with this command: curl -w "n"

      A more universal way to look up the IP address is to use the ifconfig command, on the server itself. The ifconfig command will print out information about your network interfaces. In order to narrow down the output to only the server’s public IP address, use this command (note that the highlighted part is the name of the network interface, and may vary):

      • ifconfig vtnet0 | grep "inet " | awk '{ print $2; exit }'

      You could also use curl to contact an outside party, like icanhazip, to tell you how it sees your server. This is done by asking a specific server what your IP address is:

      • curl

      Now that you have the public IP address, you may use it in your web browser’s address bar to access your web server.

      Step 2 — Installing MySQL

      Now that you have your web server up and running, it is time to install MySQL, the relational database management system. The MySQL server will organize and provide access to databases where your server can store information.

      Again, you can use pkg to acquire and install your software.

      To install MySQL 8.0 using pkg, use this command:

      • sudo pkg install mysql80-server

      Enter y at the confirmation prompt to install the MySQL server and client packages.

      To enable MySQL server as a service, add mysql_enable="YES" to the /etc/rc.conf file. You can us the sysrc command to do just that:

      • sudo sysrc mysql_enable="YES"

      Now start the MySQL server with the following command:

      • sudo service mysql-server start

      You can verify the service is up and running:

      • sudo service mysql-server status

      You’ll read something similar to the following:


      mysql is running as pid 21587.

      Now that your MySQL database is running, you will want to run a simple security script that will remove some dangerous defaults and slightly restrict access to your database system. Start the interactive script by running this command:

      • sudo mysql_secure_installation

      The prompt will ask you if you want to set a password. Since you just installed MySQL, you most likely won’t have one, so type Y and follow the instructions:

       Would you like to setup VALIDATE PASSWORD component?
      Press y|Y for Yes, any other key for No: y
      There are three levels of password validation policy:
      LOW    Length >= 8
      MEDIUM Length >= 8, numeric, mixed case, and special characters
      STRONG Length >= 8, numeric, mixed case, special characters and dictionary                  file
      Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 0
      Please set the password for root here.
      New password:  password
      Re-enter new password:  password
      Estimated strength of the password: 50
      Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y

      For the rest of the questions, you should hit the y key at each prompt to accept the recommended safe values. This will remove some sample users and databases, disable remote root logins, and load these new rules so that MySQL immediately respects the changes you’ve made.

      At this point, your database system is now set up and you can move on to installing PHP.

      Step 3 — Installing PHP

      PHP is the component of your setup that will process code to display dynamic content. It can run scripts, connect to MySQL databases to get information, and hand the processed content over to the web server to display.

      You can once again leverage the pkg system to install your components. You’re going to include the mod_php, php-mysql, and php-mysqli package as well.

      To install PHP 7.3 with pkg, run this command:

      • sudo pkg install php73 php73-mysqli mod_php73

      Enter y at the confirmation prompt. This installs the php73, mod_php73, and php73-mysqli packages.

      Now copy the sample PHP configuration file into place with this command:

      • sudo cp /usr/local/etc/php.ini-production /usr/local/etc/php.ini

      Now run the rehash command to regenerate the system’s cached information about your installed executable files:

      Before using PHP, you must configure it to work with Apache.

      Installing PHP Modules (Optional)

      To enhance the functionality of PHP, you can optionally install some additional modules.

      To see the available options for PHP 7.3 modules and libraries, you can type this:

      pkg search php73

      The results will be mostly PHP 7.3 modules that you can install:


      php73-7.3.5 PHP Scripting Language php73-aphpbreakdown-2.2.2 Code-Analyzer for PHP for Compatibility Check-UP php73-aphpunit-1.8 Testing framework for unit tests php73-bcmath-7.3.5 The bcmath shared extension for php php73-brotli-0.6.2 Brotli extension for PHP php73-bsdconv-11.5.0 PHP wrapper for bsdconv php73-bz2-7.3.5 The bz2 shared extension for php php73-calendar-7.3.5 The calendar shared extension for php php73-composer-1.8.4 Dependency Manager for PHP php73-ctype-7.3.5 The ctype shared extension for php php73-curl-7.3.5 The curl shared extension for php php73-dba-7.3.5 The dba shared extension for php php73-deployer-6.4.3 Deployment tool for PHP php73-dom-7.3.5 The dom shared extension for php ...

      To get more information about what each module does, you can either search the internet or you can look at the long description of the package by typing:

      • pkg search -f package_name

      There will be a lot of output, with one field called Comment which will have an explanation of the functionality that the module provides.

      For example, to find out what the php73-calendar package does, you could type this:

      • pkg search -f php73-calendar

      Along with a large amount of other information, you'll find something that looks like this:


      php73-calendar-7.3.5 Name : php73-calendar Version : 7.3.5 ... Comment : The calendar shared extension for php ...

      If, after researching, you decide that you would like to install a package, you can do so by using the pkg install command.

      For example, if you decide that php73-calendar is something that you need, you could type:

      • sudo pkg install php73-calendar

      If you want to install more than one module at a time, you can do that by listing each one, separated by a space, following the pkg install command, like this:

      • sudo pkg install package1 package2 ...

      Step 4 — Configuring Apache to Use PHP Module

      Apache HTTP has a dedicated directory to write configuration files into it for specific modules. You will write one of those configuration files for Apache HTTP to "speak" PHP.

      • sudo vi /usr/local/etc/apache24/modules.d/001_mod-php.conf

      Add the following lines to that file:


      <IfModule dir_module>
          DirectoryIndex index.php index.html
          <FilesMatch ".php$">
              SetHandler application/x-httpd-php
          <FilesMatch ".phps$">
              SetHandler application/x-httpd-php-source

      Now check Apache's HTTP configuration is in good condition:

      • sudo apachectl configtest

      You'll see the following output:


      Performing sanity check on apache24 configuration: Syntax OK

      Because you've made configuration changes in Apache you have to restart the service for those to be applied. Otherwise Apache will still work with the prior configuration.

      Now you can move on to testing PHP on your system.

      Step 5 — Testing PHP Processing

      In order to test that your system is configured properly for PHP, you can create a very basic PHP script.

      You'll call this script info.php. In order for Apache to find the file and serve it correctly, it must be saved under a specific directory—DocumentRoot—which is where Apache will look for files when a user accesses the web server. The location of DocumentRoot is specified in the Apache configuration file that you modified earlier (/usr/local/etc/apache24/httpd.conf).

      By default, the DocumentRoot is set to /usr/local/www/apache24/data. You can create the info.php file under that location by typing:

      • sudo vi /usr/local/www/apache24/data/info.php

      This will open a blank file. Insert this PHP code into the file:


      <?php phpinfo(); ?>

      Save and exit.

      Now you can test whether your web server can correctly display content generated by a PHP script. To try this out, you can visit this page in your web browser:


      You'll see a PHP FreeBSD testing page.

      FreeBSD info.php

      This page gives you information about your server from the perspective of PHP. It is useful for debugging and to ensure that your settings are being applied correctly.

      If this was successful, then your PHP is working as expected.

      You should remove this file after this test because it could actually give information about your server to unauthorized users. To do this, you can type this:

      • sudo rm /usr/local/www/apache24/data/info.php

      You can always recreate this page if you need to access the information again later.


      Now that you have a FAMP stack installed, you have many choices for what to do next. You've installed a platform that will allow you to install most kinds of websites and web software on your server.

      Source link

      Recommended Steps For New FreeBSD 12.0 Servers


      When setting up a new FreeBSD server, there are a number of optional steps you can take to get your server into a more production-friendly state. In this guide, we will cover some of the most common examples.

      We will set up a simple, easy-to-configure firewall that denies most traffic. We will also make sure that your server’s time zone accurately reflects its location. We will set up NTP polling in order to keep the server’s time accurate and, finally, demonstrate how to add some extra swap space to your server.

      Before you get started with this guide, you should log in and configure your shell environment the way you’d like it. You can find out how to do this by following this guide.

      How To Configure a Simple IPFW Firewall

      The first task is setting up a simple firewall to secure your server.

      FreeBSD supports and includes three separate firewalls. These are called pf, ipfw, and ipfilter. In this guide, we will be using ipfw as our firewall. ipfw is a secure, stateful firewall written and maintained as part of FreeBSD.

      Configuring the Basic Firewall

      Almost all of your configuration will take place in the /etc/rc.conf file. To modify the configuration you’ll use the sysrc command, which allows users to change configuration in /etc/rc.conf in a safe manner. Inside this file you’ll add a number of different lines to enable and control how the ipfw firewall will function. You’ll start with the essential rules; run the following command to begin:

      • sudo sysrc firewall_enable="YES"

      Each time you run sysrc to modify your configuration, you’ll receive output showing the changes:


      firewall_enable: NO -> YES

      As you may expect, this first command enables the ipfw firewall, starting it automatically at boot and allowing it to be started with the usual service commands.

      Now run the following:

      • sudo sysrc firewall_quiet="YES"

      This tells ipfw not to output anything to standard out when it performs certain actions. This might seem like a matter of preference, but it actually affects the functionality of the firewall.

      Two factors combine to make this an important option. The first is that the firewall configuration script is executed in the current shell environment, not as a background task. The second is that when the ipfw command reads a configuration script without the "quiet" flag, it reads and outputs each line, in turn, to standard out. When it outputs a line, it immediately executes the associated action.

      Most firewall configuration files flush the current rules at the top of the script in order to start with a clean slate. If the ipfw firewall comes across a line like this without the quiet flag, it will immediately flush all rules and revert to its default policy, which is usually to deny all connections. If you’re configuring the firewall over SSH, this would drop the connection, close the current shell session, and none of the rules that follow would be processed, effectively locking you out of the server. The quiet flag allows the firewall to process the rules as a set instead of implementing each one individually.

      After these two lines, you can begin configuring the firewall’s behavior. Now select "workstation" as the type of firewall you’ll configure:

      • sudo sysrc firewall_type="workstation"

      This sets the firewall to protect the server from which you’re configuring the firewall using stateful rules. A stateful firewall monitors the state of network connections over time and stores information about these connections in memory for a short time. As a result, not only can rules be defined on what connections the firewall should allow, but a stateful firewall can also use the data it has learned about previous connections to evaluate which connections can be made.

      The /etc/rc.conf file also allows you to customize the services you want clients to be able to access by using the firewall_myservices and firewall_allowservices options.

      Run the following command to open ports that should be accessible on your server, such as port 22 for your SSH connection and port 80 for a conventional HTTP web server. If you use SSL on your web server, make sure to add port 443:

      • sudo sysrc firewall_myservices="22/tcp 80/tcp 443/tcp"

      The firewall_myservices option is set to a list of TCP ports or services, separated by spaces, that should be accessible on your server.

      Note: You could also use services by name. The services that FreeBSD knows by name are listed in the /etc/services file. For instance, you could change the previous command to something like this:

      • firewall_myservices="ssh http https"

      This would have the same results.

      The firewall_allowservices option lists items that should be allowed to access the provided services. Therefore it allows you to limit access to your exposed services (from firewall_myservices) to particular machines or network ranges. For example, this could be useful if you want a machine to host web content for an internal company network. The keyword "any" means that any IPs can access these services, making them completely public:

      • sudo sysrc firewall_allowservices="any"

      The firewall_logdeny option tells ipfw to log all connection attempts that are denied to a file located at /var/log/security. Run the following command to set this:

      • sudo sysrc firewall_logdeny="YES"

      To check on the changes you’ve made to the firewall configuration, run the following command:

      • grep 'firewall' /etc/rc.conf

      This portion of the /etc/rc.conf file will look like this:


      firewall_enable="YES" firewall_quiet="YES" firewall_type="workstation" firewall_myservices="22 80 443" firewall_allowservices="any" firewall_logdeny="YES"

      Remember to adjust the firewall_myservices option to reference the services you wish to expose to clients.

      Allowing UDP Connections (Optional)

      The ports and services listed in the firewall_myservices option in the /etc/rc.conf file allow access for TCP connections. If you have services that you wish to expose that use UDP, you need to edit the /etc/rc.firewall file:

      You configured your firewall to use the "workstation" firewall type, so look for a section that looks like this:


      . . .
      . . .

      There is a section within this block that is dedicated to processing the firewall_allowservices and firewall_myservices values that you set. It will look like this:


      for i in ${firewall_allowservices} ; do
        for j in ${firewall_myservices} ; do
          ${fwcmd} add pass tcp from $i to me $j

      After this section, you can add any services or ports that should accept UDP packets by adding lines like this:

      ${fwcmd} add pass udp from any to me port_num

      In vi, press i to switch to INSERT mode and add your content, then save and close the file by pressing ESC, typing :wq, and pressing ENTER. In the previous example, you can leave the "any" keyword if the connection should be allowed for all clients or change it to a specific IP address or network range. The port_num should be replaced by the port number or service name you wish to allow UDP access to. For example, if you're running a DNS server, you may wish to have a line that looks something like this:

      for i in ${firewall_allowservices} ; do
        for j in ${firewall_myservices} ; do
          ${fwcmd} add pass tcp from $i to me $j
      ${fwcmd} add pass udp from to me 53

      This will allow any client from within the network range to access a DNS server operating on the standard port 53. Note that in this example you would also want to open this port up for TCP connections as that is used by DNS servers for longer replies.

      Save and close the file when you are finished.

      Starting the Firewall

      When you are finished with your configuration, you can start the firewall by typing:

      The firewall will start correctly, blocking unwanted traffic while adhering to your allowed services and ports. This firewall will start automatically at every boot.

      You also want to configure a limit on how many denials per IP address you'll log. This will prevent your logs from filling up from a single, persistent user. You can do this in the /etc/sysctl.conf file:

      At the bottom of the file, you can limit your logging to "5" by adding the following line:



      Save and close the file when you are finished. This will configure that setting on the next boot.

      To implement this same behavior for your currently active session without restarting, you can use the sysctl command itself, like this:

      • sudo sysctl net.inet.ip.fw.verbose_limit=5

      This should immediately implement the limit for this boot.

      How To Set the Time Zone for Your Server

      It is a good idea to correctly set the time zone for your server. This is an important step for when you configure NTP time synchronization in the next section.

      FreeBSD comes with a menu-based tool called tzsetup for configuring time zones. To set the time zone for your server, call this command with sudo privileges:

      First, you will be asked to select the region of the world your server is located in:

      FreeBSD region of the world

      You will need to choose a sub-region or country next:

      FreeBSD country

      Note: To navigate these menus, you'll need to use the PAGE UP and PAGE DOWN keys. If you do not have these on your keyboard, you can use FN + DOWN or FN + UP.

      Finally, select the specific time zone that is appropriate for your server:

      FreeBSD time zone

      Confirm the time zone selection that is presented based on your choices.

      At this point, your server's time zone should match the selections you made.

      How To Configure NTP to Keep Accurate Time

      Now that you have the time zone configured on your server, you can set up NTP, or Network Time Protocol. This will help keep your server's time in sync with others throughout the world. This is important for time-sensitive client-server interactions as well as accurate logging.

      Again, you can enable the NTP service on your server by adjusting the /etc/rc.conf file. Run the following command to add the line ntpd_enable="YES" to the file:

      • sudo sysrc ntpd_enable="YES"

      You also need to add a second line that will sync the time on your machine with the remote NTP servers at boot. This is necessary because it allows your server to exceed the normal drift limit on initialization. Your server will likely be outside of the drift limit at boot because your time zone will be applied prior to the NTP daemon starting, which will offset your system time:

      • sudo sysrc ntpd_sync_on_start="YES"

      If you did not have this line, your NTP daemon would fail when started due to the timezone settings that skew your system time prior in the boot process.

      You can start your ntpd service by typing:

      This will maintain your server's time by synchronizing with the NTP servers listed in /etc/ntp.conf.

      On FreeBSD servers configured on DigitalOcean, 1 Gigabyte of swap space is automatically configured regardless of the size of your server. You can see this by typing:

      It should show something like this:


      Device 1G-blocks Used Avail Capacity /dev/gpt/swapfs 1 0 1 0%

      Some users and applications may need more swap space than this. This is accomplished by adding a swap file.

      The first thing you need to do is to allocate a chunk of the filesystem for the file you want to use for swap. You'll use the truncate command, which can quickly allocate space on the fly.

      We'll put the swapfile in /swapfile for this tutorial but you can put the file anywhere you wish, like /var/swapfile for example. This file will provide an additional 1 Gigabyte of swap space. You can adjust this number by modifying the value given to the -s option:

      • sudo truncate -s 1G /swapfile

      After you allocate the space, you need to lock down access to the file. Normal users should not have any access to the file:

      • sudo chmod 0600 /swapfile

      Next, associate a pseudo-device with your file and configure it to mount at boot by typing:

      • echo "md99 none swap sw,file=/swapfile,late 0 0" | sudo tee -a /etc/fstab

      This command adds a line that looks like this to the /etc/fstab file:

      md99 none swap sw,file=/swapfile,late 0 0

      After the line is added to your /etc/fstab file, you can activate the swap file for the session by typing:

      You can verify that the swap file is now working by using the swapinfo command again:

      You should see the additional device (/dev/md99) associated with your swap file:


      Device 1G-blocks Used Avail Capacity /dev/gpt/swapfs 1 0 1 0% /dev/md99 1 0 1 0% Total 2 0 2 0%

      This swap file will be mounted automatically at each boot.


      The steps outlined in this guide can be used to bring your FreeBSD server into a more production-ready state. By configuring basic essentials like a firewall, NTP synchronization, and appropriate swap space, your server can be used as a good base for future installations and services.

      Source link