使用 docker-compose 管理 Node.js 项目

实际开发中,项目会在多种环境中运行,如 localdev 或者 test 等。我们可以依据不同的运行环境进行配置,使用 docker-compose 来更方便的部署应用。

项目结构

.
├── Dockerfile
├── README.md
├── config
│   ├── config.default.js
│   ├── config.dev.js
│   ├── config.local.js
│   ├── config.prod.js
│   ├── config.sandbox.js
│   ├── config.test.js
├── docker-compose.yml
├── env
│   ├── common.env
│   ├── dev.env
│   ├── local.env
│   ├── prod.env
│   ├── sandbox.env
│   └── test.env
├── package.json
├── view
└── yarn.lock

配置

# Dockerfile
FROM node:8-alpine
ADD . /code
WORKDIR /code
RUN yarn install
# docker-compose.yml
version: '2.1'
services:
  app-local:
    env_file:
      - ./env/common.env
      - ./env/local.env
    build:
      context: .
      args:
        NPM_REGISTRY: "https://registry.npm.taobao.org"
    ports:
      - "7005:7005"
    depends_on:
      - redis
    links:
      - redis
    volumes:
      - - /path/to/view:/code/view
      - ./app:/code/app
    command: ["npm", "run", "dev"]
  app-dev:
    env_file:
      - ./env/common.env
      - ./env/dev.env
    build:
      context: .
      args:
        NPM_REGISTRY: "https://registry.npm.taobao.org"
    ports:
      - "7005:7005"
    depends_on:
      - redis
    links:
      - redis
    volumes:
      - - /path/to/view:/code/view
    command: ["npm", "run", "start"]
  app-test:
    env_file:
      - ./env/common.env
      - ./env/test.env
    build:
      context: .
      args:
        NPM_REGISTRY: "https://registry.npm.taobao.org"
    ports:
      - "7005:7005"
    depends_on:
      - redis
    links:
      - redis
    volumes:
      - /path/to/view:/code/view
    command: ["npm", "run", "start"]
  app-sandbox:
    env_file:
      - ./env/common.env
      - ./env/sandbox.env
    build:
      context: .
      args:
        NPM_REGISTRY: "https://registry.npm.taobao.org"
    ports:
      - "7005:7005"
    depends_on:
      - redis
    links:
      - redis
    volumes:
      - /path/to/view:/code/view
    command: ["npm", "run", "start"]
  app-prod:
    env_file:
      - ./env/common.env
      - ./env/prod.env
    build:
      context: .
      args:
        NPM_REGISTRY: "https://registry.npm.taobao.org"
    ports:
      - "7005:7005"
    volumes:
      - /code/view
    command: ["npm", "run", "start"]
  redis:
    image: redis:3.2-alpine
    expose:
      - "6379"

部署

build 镜像

$ docker-compose build app-local
$ docker-compose build app-dev
$ docker-compose build app-prod

运行

$ docker-compose up -d app-local
$ docker-compose up -d app-dev
$ docker-compose up -d app-prod