Fun Fact: Why do Java developers wear glasses? Because they don't see sharp!
Django is a popular web framework for building web applications in Python. While the built-in development server is handy for testing your Django application during development, it's not suitable for production use. For production, you should use a production-ready web server like Gunicorn and manage it using systemd.
- Python 3 installed on your server.
- A Django project ready for production deployment.
- Virtual environment.
Inside your virtual environment, install Django and Gunicorn:
pip install gunicorn
Create a Gunicorn configuration file for your Django project. In your project directory, create a file named
gunicorn_config.py and add the following content, customizing it to your project:
bind = "127.0.0.1:8000" # Replace with your desired IP and port
workers = multiprocessing.cpu_count() * 2 + 1
worker_class = "gthread"
threads = 2
timeout = 60
Test Gunicorn to ensure it can serve your Django application. Run the following command from your project directory, replacing myproject with your Django project's name:
gunicorn -c gunicorn_config.py myproject.wsgi
If Gunicorn starts without errors, it's working correctly. You can stop it by pressing Ctrl + C.
Boom! Gunicorn is now part of our family.
Create a systemd service file to manage the Gunicorn process. Use a text editor to create a file named
myproject_gunicorn.service in the
sudo nano /etc/systemd/system/myproject_gunicorn.service
Add the following content to the file, adjusting the paths and configuration as needed:
Description=Gunicorn daemon for myproject
ExecStart=/path/to/your/virtualenv/bin/gunicorn -c gunicorn_config.py myproject.wsgi
Replace your_username, your_group,
/path/to/your/virtualenv with your actual information.
Save and exit the text editor.
Enable the systemd service and start Gunicorn:
sudo systemctl enable myproject_gunicorn
sudo systemctl start myproject_gunicorn
Check the status of the Gunicorn service to make sure it's running without errors:
sudo systemctl status myproject_gunicorn
If everything is configured correctly, your Django application should now be running in production using Gunicorn and managed by systemd. You can access it through the specified IP and port. Make sure to configure your web server (e.g., Nginx or Apache) as a reverse proxy to forward requests to Gunicorn for better security and performance in a production environment.
Until next time, keep coding and keep smiling, because development is all about making the magic happen! ✨