Step-by-Step Guide to Deploying a Django Project on a Server
1. Prepare Your Django Project
- Collect Static Files: Run the following command to gather all static files into the
STATIC_ROOTdirectory:
python manage.py collectstatic
- Set DEBUG to False: In your
settings.py, ensureDEBUGis set toFalsefor production:
DEBUG = False
- Set Allowed Hosts: Update the
ALLOWED_HOSTSsetting with your server's domain or IP:
ALLOWED_HOSTS = ['yourdomain.com', 'server_ip']
- Secure the Secret Key: Use environment variables to store sensitive data like
SECRET_KEY.
2. Set Up the Server
Install Necessary Software
- Update the Server:
sudo apt update && sudo apt upgrade -y
- Install Required Packages: Install Python, pip, and virtualenv:
sudo apt install python3 python3-pip python3-venv -y
- Install a Web Server and WSGI Server: Install
nginxandgunicorn(oruWSGI):
sudo apt install nginx
pip install gunicorn
3. Configure the Django Application
- Set Up a Virtual Environment:
python3 -m venv myenv
source myenv/bin/activate
pip install -r requirements.txt
- Test Gunicorn: Run the following command to ensure Gunicorn works:
gunicorn --bind 0.0.0.0:8000 myproject.wsgi
4. Configure Nginx
- Create an Nginx Configuration File:
sudo nano /etc/nginx/sites-available/myproject
- Add the following configuration:
server {
listen 80;
server_name yourdomain.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /path/to/your/project;
}
location / {
include proxy_params;
proxy_pass http://unix:/path/to/your/project/myproject.sock;
}
}
- Enable the Configuration:
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
sudo nginx -t
sudo systemctl restart nginx
5. Configure Gunicorn
- Create a Gunicorn Service:
sudo nano /etc/systemd/system/gunicorn.service
- Add the following:
[Unit]
Description=gunicorn daemon for Django project
After=network.target
[Service]
User=username
Group=groupname
WorkingDirectory=/path/to/your/project
ExecStart=/path/to/your/virtualenv/bin/gunicorn --workers 3 --bind unix:/path/to/your/project/myproject.sock myproject.wsgi:application
[Install]
WantedBy=multi-user.target
- Start and Enable Gunicorn:
sudo systemctl start gunicorn
sudo systemctl enable gunicorn
6. Secure the Server
- Set Up HTTPS: Install and configure Certbot for a free SSL certificate:
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com
- Renew Certificates Automatically: Add the following to
crontab:
0 3 * * * certbot renew --quiet
7. Test Your Deployment
- Visit your domain or IP in a browser to ensure the site is working.
- Check logs for any errors:
- Nginx logs:
/var/log/nginx/error.log - Gunicorn logs: Depends on your service file.
Let me know if you need assistance with any of these steps!
Comments (0)
Leave a Reply
Log in to post a comment.