如何将Django项目Docker化并部署到指定服务器IP(192.168.156.94:8000)
如何将Django项目Docker化并部署到指定服务器IP(192.168.156.94:8000)
嘿,我来一步步帮你搞定把Django项目Docker化并部署到指定IP的事儿~
第一步:完善你的Dockerfile
你已经有了基础的Dockerfile,我帮你补全并调整到适配8000端口的配置(顺便修正了一个环境变量的小错误):
# Use Python 3.12.2 image based on Debian Bullseye in its slim variant as the base image FROM python:3.12.2-slim-bullseye # Set an environment variable to unbuffer Python output, aiding in logging and debugging ENV PYTHONUNBUFFERED=1 # 调整端口为你需要的8000 ENV PORT 8000 # Set the working directory within the container to /app for any subsequent commands WORKDIR /app # Copy the entire current directory contents into the container at /app COPY . /app/ # Upgrade pip to ensure we have the latest version for installing dependencies RUN pip install --upgrade pip # Install dependencies from the requirements.txt file to ensure our Python environment is ready RUN pip install -r requirements.txt # 收集Django静态文件(如果你的项目用到静态资源的话) RUN python manage.py collectstatic --noinput # 启动Gunicorn服务器,绑定到容器的8000端口,记得替换成你实际的Django项目名 CMD ["gunicorn", "--bind", "0.0.0.0:${PORT}", "your_project_name.wsgi:application"]
⚠️ 重点:把your_project_name替换成你Django项目里wsgi.py所在的文件夹名称哦~
第二步:调整Django项目的核心配置
打开你项目里的settings.py,做两个关键修改:
允许指定IP访问:
把ALLOWED_HOSTS改成下面这样,让服务器IP能访问你的项目:ALLOWED_HOSTS = ["192.168.156.94", "localhost"](如果是测试环境,也可以暂时用
ALLOWED_HOSTS = ["*"],但生产环境不建议这么做)配置静态文件路径:
如果你用到了静态资源(比如CSS、JS),需要添加静态文件收集的目录:STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
第三步:准备好requirements.txt
确保你的requirements.txt里包含了Django和Gunicorn(用来运行生产级服务器),示例内容:
Django>=4.2 gunicorn>=21.2.0 # 其他你项目依赖的包,比如psycopg2-binary(如果用PostgreSQL)等
第四步:构建Docker镜像
在你的项目根目录(和Dockerfile同一层级),运行以下命令构建镜像:
docker build -t my-django-app .
这里的my-django-app是你给镜像起的名字,你可以改成自己喜欢的。
第五步:在目标服务器上运行容器
登录到IP为192.168.156.94的服务器,把刚才构建的镜像传上去(或者直接在服务器上拉取/构建),然后运行以下命令启动容器:
docker run -d -p 192.168.156.94:8000:8000 my-django-app
-d:让容器在后台运行-p 192.168.156.94:8000:8000:把服务器的8000端口映射到容器的8000端口,这样外部就能通过192.168.156.94:8000访问你的Django项目了
验证是否成功
打开浏览器,输入http://192.168.156.94:8000,如果能看到Django的欢迎页面或者你的项目页面,就说明部署成功啦!
备注:内容来源于stack exchange,提问作者Punreach Rany
相关产品推荐
相关产品推荐

