django – 为dev和prod分离Dockerfile的进程?

我有一个具有以下结构的项目.

ProjectName/
├── Dockerfile
├── api/
│   ├── Dockerfile
│   └── manage.py
├── docker-compose.yml
├── frontend/
│   ├── Dockerfile
│   ├── build/
│   └── src/
└── manifests/
    ├── development.yml
    └── production.yml

docker-compose.yml有一个在两个环境之间都很常见的数据库映像,而dev.yml和prod.yml对于生产和dev有相似但略有不同的映像.

示例:api dev使用django并运行python manage.py runserver,但在prod中它将运行gunicorn api.wsgi.

并且前端在npm开始运行但是在生产中我希望它基于不同的图像.目前dockerfile仅适用于其中一个,因为只有当我使用FROM节点时才会找到npm命令,而当我使用FROM kyma / docker-nginx时,nginx命令才会显示.

那么在不同的环境中如何将它们分开呢?

./frontend/Dockerfile:

FROM node

WORKDIR /app/frontend
COPY package.json /app/frontend

RUN npm install

EXPOSE 3000
CMD ["npm", "start"]

# Only run this bit in production environment, and not anything above this line.
#FROM kyma/docker-nginx
#COPY build/ /var/www
#CMD 'nginx'

./api/Dockerfile:

FROM python:3.5

RUN apt-get update \
    && apt-get install -y --no-install-recommends \
        postgresql-client \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app/api
COPY requirements.txt /app/api
RUN pip install -r requirements.txt

EXPOSE 8000

# Run this command in dev
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
# Run this command in prod
#CMD ["gunicorn", "api.wsgi", "-b 0.0.0.0:8000"]

./docker-compose.yml:

version: '3'

services:
  db:
    image: postgres
    restart: always
    ports:
  - "5432:5432"

volumes:
  node-modules:

./manifests/production.yml:

version: '3'

services:
  gunicorn:
    build: ./api
    command: ["gunicorn", "api.wsgi", "-b", "0.0.0.0:8000"]
    restart: always
    volumes:
      - ./api:/app/api
    ports:
      - "8000:8000"
    depends_on:
      - db
  nginx:
    build: ./frontend
    command: ["nginx"]
    restart: always
    volumes:
      - ./frontend:/app/frontend
      - ./frontend:/var/www
      - node-modules:/app/frontend/node_modules
    ports:
      - "80:80"

volumes:
  node-modules:

./manifests/development.yml:

version: '3'

services:
  django:
    build: ./api
    command: ["python", "manage.py", "runserver", "0.0.0.0:8000"]
    restart: always
    volumes:
      - ./api:/app/api
    ports:
      - "8000:8000"
    depends_on:
      - db
  frontend:
    build: ./frontend
    command: ["npm", "start"]
    restart: always
    volumes:
      - ./frontend:/app/frontend
      - node-modules:/app/frontend/node_modules
    ports:
      - "3000:3000"

volumes:
  node-modules:

解决方法:

根据您可以在运行时设置的环境变量,您可以使用运行一个或另一个命令的脚本作为ENTRYPOINT:

docker run -e env=DEV
# or
docker run -e env=PROD

您可以设置相同的environment variable in a docker compose file.

上一篇:【Nginx】flask + gunicorn


下一篇:gunicorn的参数详解