deploy django on nginx gunicorn
- Install required packages:
sudo apt-get update
sudo apt-get install python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx
- Create a virtual environment:
sudo apt-get install virtualenv
mkdir ~/myproject
cd ~/myproject
virtualenv myprojectenv
source myprojectenv/bin/activate
- Install Django and Gunicorn:
pip install django gunicorn
- Create a Django project:
django-admin startproject myproject
cd myproject
- Configure Django settings (update
ALLOWED_HOSTS
,DEBUG
,DATABASES
):
# myproject/settings.py
ALLOWED_HOSTS = ['your_domain_or_server_ip', 'localhost']
DEBUG = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'your_db_name',
'USER': 'your_db_user',
'PASSWORD': 'your_db_password',
'HOST': 'localhost',
'PORT': '5432',
}
}
- Migrate the database:
python manage.py migrate
- Create a superuser (optional):
python manage.py createsuperuser
- Collect static files:
python manage.py collectstatic
- Test the Gunicorn server:
gunicorn myproject.wsgi:application
- Configure Gunicorn to run as a systemd service:
sudo nano /etc/systemd/system/myproject.service
Add the following content:
[Unit]
Description=gunicorn daemon for myproject
After=network.target
[Service]
User=your_linux_username
Group=www-data
WorkingDirectory=/path/to/your/myproject
ExecStart=/path/to/your/myprojectenv/bin/gunicorn --workers=3 --bind unix:/path/to/your/myproject/myproject.sock myproject.wsgi:application
[Install]
WantedBy=multi-user.target
- Start and enable the Gunicorn systemd service:
sudo systemctl start myproject
sudo systemctl enable myproject
- Configure Nginx:
sudo nano /etc/nginx/sites-available/myproject
Add the following content:
server {
listen 80;
server_name your_domain_or_server_ip;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /path/to/your/myproject;
}
location / {
include proxy_params;
proxy_pass http://unix:/path/to/your/myproject/myproject.sock;
}
}
- Create a symbolic link to the Nginx configuration:
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
- Test Nginx configuration and restart Nginx:
sudo nginx -t
sudo systemctl restart nginx
- Adjust firewall settings if needed:
sudo ufw allow 80
sudo ufw allow 8000 # If you want to access the Django development server
sudo ufw enable
- Update your DNS records if using a domain name.
Done! Your Django application should now be deployed with Nginx and Gunicorn.