用 python3 + docker 搞 django 开发环境(zsh)

环境: 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 脚本里的版本号, 就可以继续用了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值