本地django服务容器化改造

26 阅读1分钟

通过增加一个dockerfile完成容器化改造

FROM python:3.11

WORKDIR /app

# 覆盖 apt 源为阿里云(适用于 bookworm/trixie)
RUN echo "deb http://mirrors.aliyun.com/debian trixie main contrib non-free non-free-firmware\n\
deb http://mirrors.aliyun.com/debian trixie-updates main contrib non-free non-free-firmware\n\
deb http://mirrors.aliyun.com/debian-security trixie-security main contrib non-free non-free-firmware" \
> /etc/apt/sources.list

RUN apt-get update && apt-get install -y \
    build-essential \
    libpq-dev \
    && rm -rf /var/lib/apt/lists/*

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

COPY . .

EXPOSE 8000

CMD ["sh", "-c", "python manage.py migrate && python manage.py runserver 0.0.0.0:8000"]

docker-compose.yaml同步编写

version: '3.8'
services:
  web:
    build: .
    command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000"
    ports:
      - "8000:8000"
    volumes:
      - .:/app
    environment:
      - PYTHONUNBUFFERED=1
    # Uncomment if you use a database service
    # depends_on:
    #   - db
#  db:
#    image: postgres:15
#    environment:
#      POSTGRES_DB: django_db
#      POSTGRES_USER: django
#      POSTGRES_PASSWORD: django
#    ports:
#      - "5432:5432"
#    volumes:
#      - pgdata:/var/lib/postgresql/data
#volumes:
#  pgdata:

遇到的难点在于apt镜像源的修改

# 覆盖 apt 源为阿里云(适用于 bookworm/trixieRUN echo "deb http://mirrors.aliyun.com/debian trixie main contrib non-free non-free-firmware\n\
deb http://mirrors.aliyun.com/debian trixie-updates main contrib non-free non-free-firmware\n\
deb http://mirrors.aliyun.com/debian-security trixie-security main contrib non-free non-free-firmware" \
> /etc/apt/sources.list