Photo by Kimberly Farmer on Unsplash
October 28, 2020

Deploying Sphinx to Netlify

V. David Zvenyach

Product, Hangar


Good documentation practices are important for delivery teams. And because the Hangar technical team defaults to writing in Python, we tend to use Sphinx to write our technical documentation. We have also recently been increasingly using Netlify to deploy static sites, particularly because of its excellent deploy preview feature.

For a while, I would simply manually deploy my documentation to Netlify or S3, but then I could not take advantage of the deploy preview. So, I decided to automate my sphinx builds and deploys in Netlify, and in this post I share how to do it.

The steps to deployment

There are 5 basic steps to deploying a Sphinx build to a live netlify site.

First, you need to initialize a git repository, locally and on github.

git init
gh repo create organization_name/repository_name        # This creates the github repo, and links the folder to the repo
echo "_build" > .gitignore                              # This creates a .gitignore file that ignores the `_build` directory

Second, you need to install the Sphinx dependency, both locally and in Netlify. Because sphinx is a Python library, you need to install sphinx and its dependencies. This actually involves two parts: (1) declaring that you’re going to use the Python runtime using a runtime.txt file in the root directory, and (2) identifying the dependencies that need to be installed using a requirements.txt file in the root directory. Heres’ one way to do that:

echo "3.7" > runtime.txt    # This declares that you're going to use python 3.7, not the default of python 2.7

# These commands are aiming at creating the requirements.txt file using a virtual environment
python -m venv venv
echo "venv/" >> .gitignore
source venv/bin/activate
pip install sphinx
pip freeze > requirements.txt

Third, you run sphinx-quickstart and configure your documentation. For the purposes of this project, you don’t need to split apart the source and build directories.

Fourth, you run netlify init and follow the steps to link your github repository to netlify. In this process, you’ll need to make sure that you specify make html as the build command and _build/html as the build directory.

Finally, you can commit your changes in your repo, push to github, and enjoy your newly created automated documentation pipeline.

Also, to make it easier to implement, we’ve published a bash script to easily automate the process at https://github.com/HangarOrg/sphinx-netlify-cicd. We hope you find it useful!