To create a systemd command for a Django server using Gunicorn to serve the project over some port, follow these steps:
-
Create a gunicorn configuration file. In your project directory, create a file named
gunicorn.pywith the following contents:bind = "0.0.0.0:8000" workers = 4
-
Install
Gunicornin your project environment if not yet installed.pip install gunicorn
-
Create a systemd service file. In your system's
systemddirectory (e.g./etc/systemd/systemon Linux), create a file calledmyproject.servicewith the following contents:[Unit] Description=Django Gunicorn Service [Service] User=<username> Group=<groupname> WorkingDirectory=/path/to/project ExecStart=/path/to/venv/bin/gunicorn myproject.wsgi:application --config /path/to/project/gunicorn.py Restart=always [Install] WantedBy=multi--user.targetReplace
<username>with the username of the user who should run the service, and<groupname>with the name of the user's group. Replace/path/to/projectwith the path to your Django project directory. -
Reload systemd and start the service. Run the following commands to reload systemd and start the service
sudo systemctl daemon-reload sudo systemctl start myproject.service
You can also enable the service to start automatically at boot time by running:
sudo systemctl enable myproject.service
That's it! Your Django server should now be running on port 8000 with 4 workers, managed by system. You can check the status of the service by running:
sudo systemctl status myproject.service