Django写入权限问题:Nginx/Gunicorn与Docker挂载异常排查
Django文件写入权限问题解决方案
1. 确认Gunicorn运行用户权限
Gunicorn通常不会以root用户运行,代码实际执行的用户是Gunicorn进程的运行用户,而非root:
- 执行
ps aux | grep gunicorn查看Gunicorn的运行用户(比如www-data)。 - 确保
/project/subfolder对该用户开放写入权限:- 保持目录所有者为
root:www-data的前提下,设置目录权限为775:chmod 775 /project/subfolder。 - 如果Gunicorn用自定义用户运行,将该用户加入
www-data组:usermod -aG www-data your_gunicorn_user,再设置目录权限775。
- 保持目录所有者为
2. 检查Linux安全模块限制
部分系统启用SELinux或AppArmor,会限制进程写入非默认目录:
- SELinux测试与修复:
临时关闭SELinux测试:setenforce 0,若能正常写入,添加永久规则:semanage fcontext -a -t httpd_sys_rw_content_t "/project/subfolder(/.*)?" restorecon -Rv /project/subfolder - AppArmor修复:
编辑Gunicorn的AppArmor配置文件(路径通常为/etc/apparmor.d/usr.bin.gunicorn),添加规则:
重启AppArmor生效:/project/subfolder/** rw,systemctl restart apparmor。
3. 优化代码写入逻辑
改用更安全的方式处理文件写入,避免权限问题:
- 使用Django内置的
FileSystemStorage:from django.core.files.storage import FileSystemStorage fs = FileSystemStorage(location='/project/subfolder') with fs.open('file.txt', 'w') as f: f.write(filecontent) - 手动设置文件权限:
import os from os.path import join file_path = join(DIRECTORY, 'file.txt') with open(file_path, 'w') as f: f.write(filecontent) os.chmod(file_path, 0o664) # 让组用户拥有读写权限
4. Docker挂载同步问题解决
容器默认的/tmp是独立tmpfs,无法与主机同步,需显式挂载主机目录:
docker run -v /host/project/subfolder:/container/target/path your_image
同时确保主机侧的/project/subfolder已配置好Gunicorn的写入权限,这样生成的文件会自动同步到容器。
内容的提问来源于stack exchange,提问作者zeus
相关产品推荐
相关产品推荐

