Skip to content

Instantly share code, notes, and snippets.

@kiranparajuli589
Created March 14, 2023 07:49
Show Gist options
  • Save kiranparajuli589/473f5eb642d55f57a55d9e30ba3ca18d to your computer and use it in GitHub Desktop.
Save kiranparajuli589/473f5eb642d55f57a55d9e30ba3ca18d to your computer and use it in GitHub Desktop.
how to create a systemd command for django server using gunicorn over some port

To create a systemd command for a Django server using Gunicorn to serve the project over some port, follow these steps:

  1. Create a gunicorn configuration file. In your project directory, create a file named gunicorn.py with the following contents:

    bind = "0.0.0.0:8000"
    workers = 4
  2. Install Gunicorn in your project environment if not yet installed.

    pip install gunicorn
  3. Create a systemd service file. In your system's systemd directory (e.g. /etc/systemd/system on Linux), create a file called myproject.service with 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.target
    

    Replace <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/project with the path to your Django project directory.

  4. 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment