Installing Apache Web Server on Ubuntu Desktop

0017-fi-apache-logo
In the article Installing Ubuntu Desktop on VirtualBox I demonstrated how to create a virtual machine (VM) using Oracle VirtualBox and install Ubuntu Desktop within it. Since the Desktop version of Ubuntu is targeted for workstation use rather than as a server, it does not ship with an AMP Stack (Apache, MySQL, PHP). However, if you wish to use Desktop as a standalone web development machine, it’s fairly easy to install these components yourself. In this article I’ll show you how to install Apache Web Server on Ubuntu Desktop. I’ll also provide a brief primer on configuring and managing Apache as a development web server. In future articles, I’ll demonstrate how to install and configure MySQL and PHP to build out a complete LAMP development VM. We’ll then use this environment down the road for a new WordPress series of articles.

Installing Apache Web Server

There are several tools available to manage installation of packages in Ubuntu. Ubuntu Software Center is a graphical tool that allows you to search for and install software from its configured repositories. You can launch it from the Launcher and browse software by category or search the repositories. You could also use Synaptic Package Manager (which must first be installed via Software Center). Synaptic provides more information on package versions and contents than Software Center.

You can also use Advanced Package Tool (APT) directly. As an old Unix command-line guy I like to use the command-line version of APT called apt-get. If you already know the name of the package that you want to install, I find that the command-line version is the easiest way to get it.

First, if you’re following along from the article I referenced above, ensure that your VM is started and that you are logged in as the administrative user. You must also have an active internet connection so that APT can download the Apache packages.

Next, start a terminal session by clicking the Dash icon at the top of the Launcher, entering terminal in the search box, and clicking the Terminal icon as shown below.

Launch a Terminal from the Dash

Launch a Terminal from the Dash.

This will launch the gnome-terminal application in a window on your desktop. The Terminal provides a command-line interface to Ubuntu in which you can enter commands and see the results in text format. You’ll notice that the shell prompt shows your username and machine name followed by a colon. After the colon, the shell displays your current directory (~ represents your home directory). Enter the command sudo apt-get install apache2 and press Enter. You will be prompted to enter your password. After entering your password (which will not display on the screen) and pressing Enter, APT will begin installing Apache. When you see the prompt Do you want to continue [Y/n]?, enter y and press Enter.

apt-get install command

The apt-get command-line interface to the Advanced Package Tool (APT) is a quick and easy way to install packages when you know the main package name.

After the installation completes, Apache Web Server will be installed and running (gee, that was easy). You can test the Web server by launching Mozilla Firefox by clicking its icon in the Launcher. Enter the URL http://localhost in the browser’s address bar. You should see the It works! page as shown below.

It works web page

This small HTML file shows that the Apache Web Server is operational.

sudo Voodoo
I prefixed the apt-get installation command above with the sudo command. If you’ve used Unix or some other Linux distributions, you may not be familiar with sudo (although many use it these days). Here is a brief explanation of the command and its benefits.

Unix and Linux systems have a special user called the super user with the user ID of root. The root user has full control over all aspects of the operating system including access to all files. Having all of this power makes it dangerous to do work while logged in as root. A simple misplaced space in a command could wipe out your entire system. For this reason, Ubuntu installs with the root account locked. However, as system administrator you do required root-level access to perform many activities such as installing software, managing user accounts, mounting filesystems, and changing configuration files. To accomplish these types of activities without actually logging in to the root account, Ubuntu provides the sudo command.

While running a command with sudo, Ubuntu temporarily gives you privileges associated with the root user for the duration of the command’s execution. While this command won’t necessarily prevent you from accidentally destroying your system, it does reduce the likelihood of forgetting that you’re logged in as the root user for an indefinite period of time. It also provides a bit of additional security by requiring that you enter your password every so often (every 15 minutes by default). This feature makes it less likely that you will leave a root login available for someone to exploit when you go for a cup of coffee.

Managing Apache

Entire books have been written on the topic of configuring and managing the Apache Web Server, so obviously I won’t be able to cover all of the topics in a blog post. However, I do want to demonstrate some of the basic administration tasks that you might need to perform and point out the primary configuration files that determine how Apache functions.

Command-line Options

The full path to the Apache binary is /usr/sbin/apache2. You can get a list of the command-line options it supports with the -h option:

apache2 command-line options

The -h option displays the list of command-line options available to the apache2 command.

Finding the Version

You can determine the version of Apache that is installed on your system with the -v (lowercase) option as shown below:

apache2 -v option

The -v option provides the Apache version.

You can get even more information using the -V (uppercase) option. This option will show you additional information about the compilation options that were used when building the binary from source.

apache2 -V option

The -V option provides architecture and options that were set at compilation time.

Starting and Stopping Apache

During installation Apache is configured to start automatically when Ubuntu is booted and to shutdown gracefully when Ubuntu is shut down. However, you may occasionally have the need to start up and shut down the server while the operating system is running. This is particularly true in a development environment where you may be experimenting with different Apache configuration options.

The shell script /etc/init.d/apache2 can be used to perform routine management of the Web Server. This is the shell script that is run during startup and shutdown of Ubuntu.

Let’s first check the status of the web server with the status option as shown below. This option tells us that Apache is running and its process ID (PID) is 3100.

/etc/init.d/apache2 status

You can get the current status of the server by passing the status argument to the /etc/init.d/apache2 script. The output also displays the process ID (PID) of the main, currently running process.

We can verify this by getting a listing of the apache2 processes as shown below:

apache2 daemons

You can see the process listing of the apache2 daemons by piping the output of ps through grep. The first process is the parent (owned by root) and the other three processes are children (owned by www-data).

Notice that the first of the processes listed is the one referenced in the apache2 status script output (PID 3100). This is the main process as its parent PID is 1, which corresponds to /sbin/init, the ultimate ancestor of all processes. The other apache2 processes are worker processes that are spawned by the main process. Also notice from the listing above that only the parent process is owned by root and the worker processes are owned by www-data. This is a security feature that limits the access of web application code to the www-data user and group rather than to root. Now let’s stop the web server with the stop option as shown below.

/etc/init.d/apache2 stop

The /etc/init.d/apache2 script can be used to manage the Apache server. Here, we’re stopping the server, which will kill the apache2 daemons. This is the same script that starts Apache at boot time and shuts it down when we shut down Ubuntu.

If you see the error message Could not reliably determine the server’s fully qualified domain name, using 127.0.1.1 for ServerName, create a new file in the /etc/apache2/conf.d directory with a name such as fqdn. In this file set the server name to localhost with the ServerName directive as shown below.

ServerName localhost

If you list the apache2 processes again with ps -ef | grep apache2, you should find that they have all been killed. We’ll now start Apache again with the start option as shown below.

/etc/init.d/apache2 start

Here /etc/init.d/apache2 is used to start the server by passing the start parameter.

Once the web server starts, you can run sudo /etc/init.d/apache2 status again to see the new process ID. The restart option just combines the stop and start options. If Apache was not already running it will be started. Finally, the reload option signals Apache to re-read its configuration files without actually shutting down.

apache2.conf

The main configuration file for Apache is /etc/apache2/apache2.conf. This file sets some configuration directives and also includes other files in the /etc/apache2 directory tree. The table below lists some of the directives that you may want to change.

Directive Meaning
ServerRoot Base directory for the Apache configuration. This directive is commented out in the Ubuntu default installation so the value reverts to the -D HTTPD_ROOT value that the server is compiled with: /etc/apache2
PidFile Specifies the filename of the file into which the server’s process ID is stored. On the default installation the file is /var/run/apache2.pid
Timeout The amount of time in seconds that the server waits for I/O. The default value listed in apache2.conf is 300 seconds.
KeepAlive Allows the server to provide long-lived connections on which multiple requests may be made. The value in the default installation is On.
MaxKeepAliveRequests Maximium number of requests the server is allowed to keep open per connection. The value set in apache2.conf is 100.
KeepAliveTimeout Amount of time the server will wait for a request on a connection. The configured value is 5 seconds.
User Sets the owner of the child processes that serve requests. This is set to www-data in the default Ubuntu installation.
Group Sets the group of the child processes that serve requests. This is set to www-data in the default Ubuntu installation.
AccessFileName Name of the per-directory configuration file. The value established in apache2.conf is .htaccess.
DefaultType Sets the default content-type of files that the server cannot determine. The value set is None.
HostnameLookups Enables DNS lookups of IP addresses so that host names can be logged and passed to CGI programs. This is set to Off by default.
ErrorLog Sets the filename in which the server will record error messages. The installation value is /var/log/apache2/error.log.
LogLevel Controls the number and types of messages logged to the error log. The default value is set to warn.
LogFormat Defines a nickname for a log format to be used in the access log. Several different nicknames are setup in apache2.conf.

envvars

You’ll find that many of the directives reference environment variables. These are maintained in the /etc/apache2/envvars script, which is called by several Apache administration utilities. Below, are the environment variables set in this file along with their values.

Variable Value
APACHE_RUN_USER www-data
APACHE_RUN_GROUP www-data
APACHE_PID_FILE /var/run/apache2.pid
APACHE_RUN_DIR /var/run/apache2
APACHE_LOCK_DIR /var/lock/apache2
APACHE_LOG_DIR /var/log/apache2

ports.conf

The main configuration file, apache2.conf, includes ports.conf that defines what ports Apache listens on. The file contains two directives as listed below:

Directive Meaning
NameVirtualHost Defines a name-based virtual host IP address and port. The installed value *:80 tells Apache that it should listen on port 80 of all interfaces for requests.
Listen Instructs Apache to listen on specific IP addresses and ports. The default value of 80 tells Apache to listen on port 80 (the standard HTTP port) for requests. If SSL is enabled, the server will also listen on port 443.

mods-enabled

The apache2.conf file also includes files in the mods-enabled subdirectory. Files in this directory are actually symbolic links to files in the mods-available subdirectory. This arrangement allows you to easily activate and de-activate modules by simply creating or removing the symlinks. However, the a2enmod and a2dismod utilities should be used to perform this activity.

Within the /etc/apache2/mods-enabled directory, the *.load files contain a directive to load the associated module, while the *.conf files contain directives to configure the modules. I won’t go through all of the possible modules that can be loaded into Apache, but the table below provides a list of the currently enabled “mods.”

Module Purpose
core Core Apache features and functions.
http_core Base module of Apache in which all core functionality is implemented.
mod_alias Provides for mapping different parts of the host filesystem in the document tree and for URL redirection.
mod_auth_basic Provides for basic authentication.
mod_authn_file Provides user authentication using text files.
mod_authz_default Authorization fallback module.
mod_authz_groupfile Provides group authorization using text files.
mod_authz_host Provides group authorizations based on hostname or IP address.
mod_authz_user Provides user authorization.
mod_autoindex Generates directory indexes.
mod_cgid Execution of CGI scripts using an external CGI daemon.
mod_deflate Compresses content before it is delivered to the client.
mod_dir Provides for “trailing slash” redirects and serving directory index files.
mod_env Modifies the environment which is passed to CGI scripts and SSI pages.
mod_log_config Logging of server requests.
mod_log_io Logging of number of bytes sent and received.
mod_mime Associates the requested filename’s extensions with the file’s behavior (handlers and filters) and content (mime-type, language, character set and encoding).
mod_negotiation Provides for selection of the document that best matches the client’s capabilities.
mod_reqtimeout Set timeout and minimum data rate for receiving requests.
mod_setenvif Allows the setting of environment variables based on characteristics of the request.
mod_sos Loads modules via dynamic shared objects.
mod_status Provides information on server activity and performance.
mod_version Allows testing Apache version with <IfVersion> directive.
worker Multi-processing module (MPM) that implements a hybrid multi-process and multi-threaded server architecture.

sites-enabled

Virtual hosts allow the Apache Web Server to serve multiple web sites with a common set of processes. The apache.conf file configures virtual hosts by including files from the sites-enabled subdirectory. Similar to modules, this subdirectory contains symlinks to files in the sites-available subdirectory. Sites can be activated and de-activated by adding and removing these symlinks. However, the a2ensite and a2dissite utilities should be used to perform these actions.

Each file in the /etc/apache2/sites-enabled directory configures a particular virtual host. The default Apache installation on Ubuntu includes one virtual host configured by the 000-default configuration file, which is linked to default in the sites-available directory. The directives included in the virtual host configuration file are listed in the table below:

Directive Meaning
ServerAdmin Specifies the administrator’s contact email address to be sent in error responses. The value set at installation is webmaster@localhost.
DocumentRoot Sets the base directory from which Apache will serve files. The installed value for the default site is /var/www. Subdirectories of /var/www are mapped to URL path components. Additional locations in the filesystem can be included with directives such as Alias and AliasMatch.
<Directory> <Directory> and </Directory> enclose a group of directives that apply to the directory listed. Wildcards are allowed to form a directory path specification. The installed default site sets up three directories: /, /var/www/, and /usr/lib/cgi-bin.
Options This directive controls what features are available in a particular directory. It can have the values: None, All, ExecCGI, FollowSymLinks, Includes, IncludesNOEXEC, Indexes, MultiViews, and SymLinksIfOwnerMatch. Option values can be preceded by + (to add the option) or – (to remove the option).
AllowOverride This directive controls which directives in effect for a directory can be overridden by an .htaccess file in that directory.
Order Specifies the order of evaluation of Allow and Deny directives. The values an be Allow,Deny or Deny,Allow.
Allow Specifies which hosts are allowed access to a directory. The value can be All or full/partial hostnames/IP addresses or the value of an environment variable.
Deny Specifies which hosts are denied access to a directory. The value can be All or full/partial hostnames/IP addresses or the value of an environment variable.
ScriptAlias Establishes an alias for a CGI script directory.
ErrorLog Specifies the path and filename to which the server will log error messages.
LogLevel Controls the number and types of messages logged to the error log. The default value is set to warn.
CustomLog Specifies a file to which access log messages will be written and/or the nickname of a particular LogFormat to be used.

Viewing Logs

While running, Apache logs activity and diagnostic information the access.log and error.log files, respectively. By default, these files are stored in the /var/log/apache2 directory.

Managing Content

The content of each site managed by Apache is stored in the directory specified by the DocumentRoot directive. By default, the document root on Ubuntu is /var/www. This directive is specified in the 000-default virtual host configuration file discussed earlier. If you take a look in the /var/www directory immediately after installing Apache, you will find a single file, index.html. If you view the contents of this file, you will see that it contains the HTML to display the “It works!” message we saw earlier.

DocumentRoot directory

The DocumentRoot directory for the default install is /var/www. It contains a single test page called index.html. This file will be displayed by the browser if you navigate to the main site URL.

Adding content to the web site is as simple as updating this file and/or adding new files to the /var/www directory. As an example, let’s create a small “Hello, world!” HTML file in the document root using the vi editor (see below for a cheat sheet of vi keystrokes).

New HTML file in DocumentRoot

We use the vi editor to create a new HTML file in the DocumentRoot called hello.html.

Enter the HTML shown below in the file. This HTML page displays the text Hello, world!.

hello.html contents

This web page will just display the famous Hello, world! message.

The vi Editor
To create the HTML file above I’m using the vi editor. This is one of several text editors available to you. Here is a quick list of the most common vi commands to get you started:

Esc
Return to command mode.
i
Insert new text in front of current cursor position. Press Esc to end insertion mode.
a
Append new text after current cursor position. Press Esc to end append mode.
x
Delete character under cursor.
dd
Delete entire line under cursor.
r
Replace one character at cursor position with next character typed.
R
Replace existing text as it is typed. Press Esc to exit replace mode.
u
Undo the last change.
U
Restore the current line as it was before last change.
Y
Copy (yank) the current line into text buffer.
p
Paste (put) the text buffer before the cursor position.
P
Paste (put) the text buffer after the cursor position.
h
Move cursor left one position (arrow keys should also work).
l
Move cursor right one position (arrow keys should also work).
j
Move cursor down one line (arrow keys should also work).
k
Move cursor up one line (arrow keys should also work).
o
Open a new line below the current cursor and enter insertion mode. Press Esc to end insertion mode.
O
Open a new line aboce the current cursor and enter insertion mode. Press Esc to end insertion mode.
ZZ
Terminate the editing session and save the file.
:w
Save (write) the file using the current filename.
:w filename
Write the file to filename.
:q
Quit if the file has been saved.
:q!
Quit and discard the file.
/text
Search for text.

You can view the new HTML file by entering the URL http://localhost/hello into the browser’s address bar as shown below.

Hello, world page

The new web page can be accessed as http://localhost/hello.

You can also create subdirectories under the document root to hold different types of files like images, style sheets, and javascript files. You can also use subdirectories to create a hierarchy of pages such as products, services, resources, and help. As an example, let’s create a subdirectory within the document root called products. We’ll then create a new HTML file in the products directory called widget.html as shown below.

New DocumentRoot subdirectory

We now create a subdirectory within DocumentRoot and create a new HTML file in it.

Enter the following HTML into the file.

widget.html contents

This simple HTML file will display a short message.

You can access this page by including the products component in the URL as shown below:

Web page output of widgets.html

The products subdirectory maps to a products component in the URL.

Installing the Apache Documentation

You can install Apache’s web-based documentation package using the apache2-doc package. The package contains reference and tutorial information on configuring and managing the server. In a terminal window, execute the command sudo apt-get install apache2-doc as shown below.

apache2-doc package installation

You can install Apache documentation using the apache2-doc package.

Once the installation completes, you can access the documentation by typing http://localhost/manual into your browser’s address bar as shown below.

Apache documentation page

The Apache documentation can be viewed with the URL http://locahost/manual.

The documentation itself is installed in /usr/share/doc/apache2-doc/manual. A new script called apache2-doc is installed in /etc/apache2/conf.d. This script creates the alias /manual to the documentation directory and allows access to it with a <Directory> directive as shown below.

Alias for Apache documentation

An alias is created as /manual so that the documentation can be accessed as http://localhost/manual. However, it is actually stored in the /usr/share/doc/apache2-doc/manual directory.

In this article I showed how easy it is to install the Apache Web Server on Ubuntu Desktop. We then took a tour of the installation, examining several of the configuration files and trying out the commands to startup and shutdown the web server. We then created a few simple HTML files and requested them from Apache using a web browser. Finally, we installed the Apache documentation package and looked at its Alias and <Directory> configuration.

In future articles I’ll demonstrate how to complete the build out of a LAMP development server by installing and integrating MySQL and PHP with Apache. We’ll also install WordPress and some development tools on the platform before using it for an upcoming project.

Speak Your Mind

*