This script automates the setup of a systemd service for a Django project running on Gunicorn. It's ideal for deploying Django applications in a production Linux environment with minimal manual setup.
- Scans user home directories for Django projects (
manage.py) - Detects virtual environments and WSGI modules automatically
- Prompts for safe defaults with validation
- Installs Gunicorn if not already installed
- Creates a systemd service file under
/etc/systemd/system/ - Enables and starts the service with proper permissions
- Colour-coded prompts and messages for clarity
-
Linux-based system (tested on Ubuntu/Debian)
-
Python 3.6+
-
Root privileges (to write to
/etc/systemd/system/) -
Django project with:
- A
manage.pyfile - A valid
wsgi.pyfile - A working virtual environment
- A
- Asks you to choose a system user and group to run the service
- Detects Django projects in
/home/<user>/ - Detects or prompts for the virtual environment path
- Detects or prompts for the WSGI module
- Asks for IP and port to bind Gunicorn
- Installs Gunicorn inside the virtual environment if needed
- Writes a
.servicefile forsystemd - Reloads
systemd, enables, and starts the service
sudo ./create_gunicorn_service.py
⚠️ Must be run as root (or usingsudo) to write systemd service files.
[Unit]
Description=Gunicorn daemon for myapp
After=network.target
[Service]
User=myuser
Group=mygroup
WorkingDirectory=/home/myuser/myproject
ExecStart=/home/myuser/myproject/venv/bin/gunicorn --workers 3 --bind 127.0.0.1:8000 myproject.wsgi:application
Restart=on-failure
SuccessExitStatus=143
[Install]
WantedBy=multi-user.targetsudo systemctl restart <service_name> # Restart service
sudo systemctl status <service_name> # Check service status
journalctl -u <service_name> -f # Follow logs- For public access, bind to
0.0.0.0, but it's recommended to use127.0.0.1with a reverse proxy like Nginx. - Avoid running as
root. Choose a dedicated non-root user. - You can re-run the script to overwrite or update an existing service.
Always keep your virtual environment isolated and make sure only trusted users have access to modify Django code or systemd service files.