在EC2(Amazon Linux 2)上部署Django项目

174 阅读5分钟

1.conda下载

远程登录Amazon Linux 2后

# 下载安装脚本
sudo wget https://repo.anaconda.com/archive/Anaconda3-2024.06-1-Linux-x86_64.sh

# 修改环境变量
sudo vim  ~/.bashrc

# 设置语言
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

# 修改路径
export PATH="~/anaconda3/bin:$PATH"

# 更新配置文件
source ~/.bashrc

# 执行脚本
bash ./Anaconda3-2024.06-1-Linux-x86_64.sh -b

# 删除脚本
sudo rm -rf Anaconda3-2024.06-1-Linux-x86_64.sh

# 查看版本
conda --version

如果不修改UTF-8的环境变量,执行脚本时可能会报错RuntimeError: Failed to extract /root/anaconda3/pkgs/sphinx-7.3.7-py312h5eee18b_0.conda: 'ascii' codec can't encode character '\xe4' in position 90: ordinal not in range(128)。由于 ascii 编码问题 , conda 在解压包时遇到了一些非 ASCII 字符(如中文或其他非英文字符),但 Python 尝试用 ascii 编码处理路径或文件名时失败了。这次用的conda版本为conda 24.5.0

创建名为dajngo_env的虚拟环境

conda create --name django_env python=3.10
conda init
source ~/.bashrc
conda activate django_env

2.httpd下载

安装Apache HTTP 服务器(httpd

# 下载apache
sudo yum install httpd -y

# 开启服务,默认监听 80 端口
sudo systemctl start httpd

# 开机自启
sudo systemctl enable httpd

# 查看状态
sudo systemctl status httpd

# 测试/etc/httpd/conf/httpd.conf的配置文件是否正确
sudo httpd -t

# 监听80端口
sudo lsof -i :80
COMMAND  PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
httpd   3651   root    4u  IPv6  29250      0t0  TCP *:http (LISTEN)
httpd   3652 apache    4u  IPv6  29250      0t0  TCP *:http (LISTEN)
httpd   3654 apache    4u  IPv6  29250      0t0  TCP *:http (LISTEN)
httpd   3659 apache    4u  IPv6  29250      0t0  TCP *:http (LISTEN)
httpd   3661 apache    4u  IPv6  29250      0t0  TCP *:http (LISTEN)
httpd   3666 apache    4u  IPv6  29250      0t0  TCP *:http (LISTEN)

安装完成后,可以在浏览器访问服务器的公网 IP 地址(如 http://your-server-ip)查看默认 Apache 页面

  • 错误日志:/var/log/httpd/error_log

  • 访问日志:/var/log/httpd/access_log

从本地上传Django项目到Amazon服务器上

scp -i ~/.ssh/ec2 ~/Downloads/django_app.zip ec2-user@18.183.29.171:~/django_app.zip

移动django项目到/var/www目录下

#  复制
sudo cp ~/django_app.zip /var/www/django_app.zip

# 解压
sudo unzip /var/www/django_app.zip

在 Amazon EC2 上,ec2-user 通常没有权限直接向 /var/www 等系统目录写入文件,因为这些目录通常属于 root 用户,为了绕过这个权限限制,将文件上传到 ec2-user 可以访问的目录,然后通过 sudo 将文件移动到目标目录

3.修改Django配置

修改settings.py

sudo vim /var/www/django_app/django_app/settings.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'HOST': '127.0.0.1', 
    'PORT': 3306, 
    'USER': 'root',  
    'PASSWORD': '[你的密码]', 
    'NAME': '[你的数据名]'
    }
}

安装依赖项

pip install -r requirement.txt

查看django是否安装成功

pip show django

Name: Django
Version: 5.0.7
Summary: A high-level Python web framework that encourages rapid development and clean, pragmatic design.
Home-page: https://www.djangoproject.com/
Author: Django Software Foundation
Author-email: foundation@djangoproject.com
License: BSD-3-Clause
Location: /root/anaconda3/envs/django_env/lib/python3.10/site-packages
Requires: asgiref, sqlparse
Required-by: django-ckeditor, django-cors-headers, django-js-asset, django-redis, django-simpleui, django_csp, djangorestframework, djangorestframework-simplejwt

静态文件收集

python manage.py collectstatic

数据库迁移

python manage.py makemigrations
python manage.py migrate

测试django项目能否运行

# 关闭80端口
sudo systemctl stop httpd

# 开启dajngo服务
python manage.py runserver 0.0.0.0:80

3.uwsgi下载

conda下载uWSGI

conda install uwsgi

# 查看版本
conda list uwsgi

Name                    Version                   Build  Channel
uwsgi                     2.0.21          py310h32d3c7e_4  

在项目根目录下创建uwsgi.ini文件,并添加如下代码

sudo vim uwsgi.ini

[uwsgi]
http = 127.0.0.1:8000
chdir = /var/www/django_app
wsgi-file = %(chdir)/django_app/wsgi.py
processes = 4
threads = 2
vacuum = true
buffer-size = 65536
master = true
stats=%(chdir)/uwsgi.status
pidfile=%(chdir)/uwsgi.pid

测试uWSGI能否运行,在项目根目录下输入下面指令,如果出现一下输出,表示uWSGI能运行

uwsgi --ini uwsgi.ini 

WSGI app 0 (mountpoint='') ready in 1 seconds on interpreter 0x1fbbd00 pid: 4576 (default app)
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** 
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 4576)
spawned uWSGI worker 1 (pid: 4577, cores: 2)
spawned uWSGI worker 2 (pid: 4579, cores: 2)
spawned uWSGI worker 3 (pid: 4580, cores: 2)
spawned uWSGI worker 4 (pid: 4582, cores: 2)
*** Stats server enabled on /var/www/django_init/uwsgi.status fd: 15 ***
^CSIGINT/SIGTERM received...killing workers...
worker 1 buried after 1 seconds
worker 2 buried after 1 seconds
worker 3 buried after 1 seconds
worker 4 buried after 1 seconds

4.配置httpd

# 开启服务
sudo systemctl start httpd

需要在 Apache 上配置代理以将请求转发给 uWSGI,并且设置静态文件和媒体文件的路径,创建一个新的配置文件 /etc/httpd/conf.d/django.conf,并加入以下内容

<VirtualHost *:80>
    ServerName your_domain_or_ip

    # 静态文件
    Alias /static/ /var/www/django_app/staticfiles/
    <Directory /var/www/django_app/staticfiles/>
        Require all granted
    </Directory>

    # 媒体文件
    Alias /media/ /var/www/django_app/media/
    <Directory /var/www/django_app/media>
        Require all granted
    </Directory>

    <Directory /var/www/django_app>
        Require all granted
    </Directory>

    # 使用简单的 HTTP 代理
    # ProxyPass / http://127.0.0.1:8000/
    # ProxyPassReverse / http://127.0.0.1:8000/

    # 禁止根路径 `/` 和非 Django 路径被代理
    ProxyPass /static !
    ProxyPass /media !
    ProxyPass /secret !
    ProxyPass / !

    # 仅将 /v1/ 代理到 Django 后端
    ProxyPass /v1/ http://127.0.0.1:8000/v1/
    ProxyPassReverse /v1/ http://127.0.0.1:8000/v1/

    ErrorLog /var/log/httpd/django_error.log
    CustomLog /var/log/httpd/django_access.log combined
</VirtualHost>

重启httpd

# 测试
sudo httpd -t

# 重启
sudo systemctl restart httpd

5.开启Django服务

在项目根目录下运行

uwsgi --ini uwsgi.ini

浏览器访问http://[your_domain_or_ip]

6.screen

要确保 Django 项目通过 uWSGI 在远程 EC2(Amazon Linux 2) 上 24 小时稳定运行,并且不受本地计算机电源状态的影响,可以通过以下步骤配置 下载screen

# Debian/Ubuntu 
sudo apt-get install screen  

# CentOS/Amzon Linux 2
sudo yum install screen 

创建名为my_django_app 的screen会话

# screen  
screen -S my_django_app 

连接会话

screen -ls
screen -r my_django_session

如果要退出会话,在screen会话里输入exit

7.相关文章