步骤 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 #启动容器
标签:root,image,django,构建,mysql,镜像,docker,8000
From: https://www.cnblogs.com/win1998/p/18512944