环境: macbook
前置准备
brew install docker
docker pull python:3.8
在项目根目录下新建 Dockerfile
Dockerfile
# Use an official Python runtime as a parent image
FROM python:3.8
# Install Node.js, 这时因为代码里有一部分 nodejs 相关的部分, 不通用, 先注释掉
RUN apt-get update && apt-get install -y curl && \
curl -sL https://deb.nodesource.com/setup_14.x | bash - && \
apt-get install -y nodejs
# Set the working directory to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . /app
# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
# Make port 80 available to the world outside this container
EXPOSE 80
# Run app.py when the container launches
CMD ["python", "./app.py"]
出来 build image
docker build -t my_django_app:1.0 .
新建一个跑容器的脚本
py38.sh
#!/bin/zsh
# This assumes the name of the Docker image is python:3.8
docker run -it --rm -v "$PWD":/usr/src/app -v /path/on/your/host:/path/in/your/container --add-host=host.docker.internal:host-gateway -w /usr/src/app my_django_app:1.0 python "$@"
-v “$PWD”:/usr/src/app
把当前路径丢里头去, 就把 python3 这个命令要跑的文件给搞里头
-v /path/on/your/host:/path/in/your/container
把自己机器上放配置文件的路径,比如什么 api-key 啊这些文件的路径给丢 container 里头去
–add-host=host.docker.internal:host-gateway
这行是为了在 container 里面访问宿主机上的 mysql, 不然跑不了 python3 manage.py makemigrations
这里还要配合 local settings, 里面把 database 相关的东西配置一下
-w /usr/src/app
work dir
local_settings.py 关于数据库的配置
# docker db config
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': 'host.docker.internal',
'PORT': '3306',
'...': '...',
}
}
用软连接搞一个脚本的快捷方式
ln -s <path_to_py3_script> /usr/local/bin/py38
成功!
py38 manage.py shell
py38 manage.py makemigrations
py38 --version
别的有的没的
每次更新 requirements, 重新 build 下 image, 改一下 py38 脚本里的版本号, 就可以继续用了