We hope you find this tutorial helpful. In addition to guides like this one, we provide simple cloud infrastructure for developers. Learn more →

How to Run a Django Site with Apache, mod_wsgi, and MySQL on FreeBSD 10.1

PostedMay 29, 2015 27.3k views Django MySQL Apache FreeBSD

Introduction

This article shows you how to deploy a web application using Django, the popular Python framework. The beauty of developing with popular web frameworks is that a lot of repetitious work has been done for you, so you can focus on building your site.

Whether you're a developer or not, it's great to know that the core of what you're running on your Droplet has undergone the scrutiny of a large open-source community and should be less susceptible to large security holes.

One thing that is not inherently simple is knowing how to get these web frameworks up and running outside of your own development or testing environment. In this article we'll show you how to do just that, using a standard Apache, mod_wsgi, and MySQL stack running on top of FreeBSD 10.1.

Goals

  • Install and configure a Python virtual environment for your Django site
  • Create and configure a sample Django site for testing
  • Configure a simple and secure MySQL server
  • Configure a simple Apache virtual host that will serve your Django site
  • Test that the newly minted site works properly

Prerequisites

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

  • A FreeBSD 10.1 Droplet
  • Access to your root account or an account with sudo privileges following this tutorial
  • A working knowledge of how to edit text files from the command line
  • The Bash shell environment, since we'll be using Virtualenv later on this tutorial. Follow the instructions in the Changing the Default Shell section of the How To Get Started with FreeBSD 10.1 tutorial. You may need to log out and log in again to get the Bash shell for your freebsd user

Step 1 — Install and Configure a Python Virtual Environment

First things first; ensure your current packages are up to date.

  • sudo pkg update && sudo pkg upgrade -y

Now install all the packages you need by running the following command and saying yes to the resulting prompt. You'll notice that far more than what we typed is installed, as the pkg system calculates and selects all the right dependencies.

  • sudo pkg install bash ap24-mod_wsgi3 py27-virtualenv mysql56-server

The virtualenv command you'll be using soon doesn't play nicely with the default user tcsh shell in FreeBSD. We need bash instead. If you're coming from a Linux environment you'll feel right at home. If you didn't do this already in the prerequisites, please follow the instructions here now.

Are you running the Bash shell now? Remember to log out and log in again. Great!

Now let's get started on our Python environment.

To make things easy to find, create a directory for your site by issuing this command.

  • sudo mkdir -p /www/data/www.example.com

Give your user account access to work in your new project directory. The whoami portion of the command automatically fills in your current username.

  • sudo chown -R `whoami` /www/data/www.example.com

Change to your newly created directory.

  • cd /www/data/www.example.com

Using per site or per application virtual environments allows customizing which Python packages and versions you install, rather than having things installed on a system-wide level.

Now create the python virtual environment using the virtualenv utility.

  • virtualenv venv

Activate that environment to make sure you're installing requirements for your Django site in that environment rather than at a system-wide level.

  • source venv/bin/activate

You'll know that you're in the right environment when you see your command prompt prefaced with (venv).

If everything looks in order, make sure Python's tools are up to date to complete this step.

  • pip install -U setuptools pip

Step 2 — Create and Configure a Sample Django Site

Now you can create the beginnings of a Django site. You'll begin by installing the python requirements that are needed to run the site. Make sure you're still in the /www/data/www.example.com directory and in your virtual environment.

  • pip install django mysql-python

With Django and MySQL support for Python installed, it's time to create the project layout using Django's django-admin utility.

  • django-admin.py startproject mysite .

Using your favorite editor, open the mysite/settings.py file.

  • vi /www/data/www.example.com/mysite/settings.py

Change the DATABASES section to look like this. Make sure you replace password with something more secure.

/www/data/www.example.com/mysite/settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mysite',
        'USER': 'mysite',
        'PASSWORD': 'password',
        'HOST': '/tmp/mysql.sock',
    }

Save your changes.

Step 3 — Configure a Simple and Secure MySQL Server

You've already installed MySQL, so now it just needs to be configured.

First, a bit of housekeeping. Open the /etc/rc.conf file for editing.

  • sudo vi /etc/rc.conf

Add these two lines to the bottom of the file. This makes sure MySQL and Apache will start when the server is started.

/etc/rc.conf
mysql_enable="YES"
apache24_enable="YES"

We haven't configured Apache just yet, but it's easier to add both lines now so you don't forget later.

Start up the MySQL server instance.

  • sudo service mysql-server start

Run this command to secure your database server.

  • mysql_secure_installation

Read all the prompts (for your own knowledge), and answer Y to all except the password selection. For the password prompts, please set the root MySQL password to something secure.

Log in to your new and reasonably secure MySQL instance, using the password you just set.

  • mysql -u root -p

Execute this command to create the sample site database, called mysite.

  • create database mysite character set utf8;

Now use this command to create the mysite database user and grant it permissions to the database you just created. Make sure password matches what you set in the settings.py file earlier. In fact, you can change the database name and username too if you want; just make sure the database and user you create match the settings in the Python configuration file.

  • grant all privileges on mysite.* to 'mysite'@'localhost' identified by 'password';

If you don't see any errors, you can quit the MySQL shell like this:

  • quit

Now that the database is ready, you'll use the Django manage.py utility to populate it with your sample site's initial data. Again, this has to be done from the site's directory, /www/data/www.example.com.

  • ./manage.py migrate

(Optional) Step 4 — Test the New Django Application

Before we go further let's make sure that the sample Django site is in working order.

Start the Django development server, allowing it to listen on your Droplet's public network interface.

  • ./manage.py runserver 0.0.0.0:8000

In your DigitalOcean Droplet panel, find the external IP address of your Droplet. Now, in your browser visit http://<your ip here>:8000. You should see the default page for a new Django installation.

It's very important that you press CTRL+C on your keyboard to quit the Django development server, as it is not to be used in production.

A Note on Security

There's a lot to read about security and best practices when running any site. To run something real in production, it's highly recommended that you do additional reading on how to properly secure a public facing web server and database server.

With that public service announcement out of the way, it's time to configure Apache to serve our Django site.

Step 5 — Configure a Simple Apache Virtual Host For Your Django Site

Using your favorite editor, create and edit the /usr/local/etc/apache24/Includes/httpd.conf file:

  • sudo vi /usr/local/etc/apache24/Includes/httpd.conf

Add all of the following configuration settings to create your virtual host. Please replace www.example.com with your website name to match the directories we created earlier.

/usr/local/etc/apache24/Includes/httpd.conf
# Settings
ServerName mysite

## Default Overrides
ServerSignature Off
ServerTokens Prod
Timeout 30

## Virtual Hosts
<VirtualHost *:80>

    WSGIDaemonProcess mysite python-path=/www/data/www.example.com:/www/data/www.example.com/venv/lib/python2.7/site-packages/
    WSGIProcessGroup mysite
    WSGIScriptAlias / /www/data/www.example.com/mysite/wsgi.py

    <Directory /www/data/www.example.com/mysite>
        <Files wsgi.py>
        Require all granted
        </Files>
    </Directory>

</VirtualHost>

Here you're simply telling Apache to set a couple of sane default configuration options and where to find the Python code to launch the Django site using Apache's mod_wsgi module. This article has a greater level of detail about Apache virtual hosts, if you want to read more.

Start up the Apache web server.

  • sudo service apache24 restart

Testing the Sample Django Site

You should now be able to visit http://your_server_ip from your browser and see the default Django page. If you've set up DNS, you can also use your domain.

Conclusion

As you can see, there is a lot to learn around the topic of deploying even the simplest websites and applications. The next step is to deploy your custom application, instead of the demo application we used in the tutorial.

If you have any questions or comments, please leave them below.

The following links can help you learn more about building and deploying a simple Django site.

12 Comments

Creative Commons License