django 项目构建镜像
步骤 1:创建项目文件
首先,确保在项目目录下有以下三个文件:
- Dockerfile
- docker-compose.yml
- requirements.txt
# Use the official Python image from the Docker Hub
FROM python:3.9
# Set the working directory in the container
WORKDIR /app
# Copy the requirements.txt file into the container
COPY requirements.txt .
# Install the dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Copy the entire Django project into the container
COPY . .
# Expose the port the app runs on
EXPOSE 8000
# Command to run the application
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
version: '3.8'
services:
db:
image: mysql:latest
volumes:
- mysql_data:/var/lib/mysql
environment:
MYSQL_DATABASE: db1
MYSQL_USER: root
MYSQL_PASSWORD: root
MYSQL_ROOT_PASSWORD: root
ports:
- "3306:3306"
web:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/app
ports:
- "8000:8000"
depends_on:
- db
environment:
- DATABASE_URL=mysql://root:root@db/db1
volumes:
mysql_data:
Django>=3.0,<4.0
mysqlclient
步骤 2:安装docker desktop
配置镜像源
setting -> Docker Engine
"registry-mirrors": [
"https://dockerproxy.com",
"https://docker.mirrors.ustc.edu.cn",
"https://docker.nju.edu.cn"
]
步骤 3:构建和运行 Docker 容器
打开 PowerShell 或 CMD,导航到项目的根目录,确保 Dockerfile 和 docker-compose.yml 都在此目录下。
执行以下命令来构建和启动容器:
docker-compose up --build
注意:如果你的项目依赖数据库服务(例如 MySQL),仍需在新电脑上配置 docker-compose.yml 或者手动启动数据库容器,以确保与项目镜像的兼容性。
#拉取并运行镜像(无需项目文件的情况操作步骤) 或者复制项目,新增最开始提到的那三个文件,用build的方式启动
docker save -o myproject_image.tar your_image_name:tag #导出并传输镜像
docker load -i myproject_image.tar #在新电脑上导入镜像
docker run -d -p 8000:8000 your_image_name:tag #启动容器
本文作者:林汉州win
本文链接:https://www.cnblogs.com/win1998/p/18512944
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效