为什么Dockerfile不运行多个命令

时间:2018-04-19 03:16:33

标签: docker docker-compose dockerfile

我想用Docker运行我的项目(react + nodejs + mongodb), this is my project directory

Dockerfile:

FROM node:8.9-alpine

ENV NODE_ENV production

WORKDIR /usr/src/app

COPY ["package.json", "package-lock.json*", "npm-shrinkwrap.json*", "./"]

RUN npm install --production --silent && mv node_modules ../

COPY . .

CMD nohup sh -c 'npm start && node ./server/server.js'

搬运工-compose.yml:

version: '2.1'

services:
  chat:
    image: chat
    container_name: chat
    build: .
    environment:
      NODE_ENV: production
    ports:
      - "3000:3000"
      - "8080:8080"
    volumes:
      - ./:/usr/src/app
    links:
      - mongo
  mongo:
    container_name: mongo
    image: mongo
    ports:
      - "27017:27017"

运行docker-compose up --build,3000端口工作,但是8080端口死了

localhost:3000

localhost:8080

2 个答案:

答案 0 :(得分:0)

我建议为服务器创建一个容器,并将其与“chat”容器分开。最好让每个容器只做一件事和一件事(几乎就像unix命令背后的哲学)

在任何情况下,我都会对撰写文件进行一些修改。

version: '2.1'

services:
  chat:
    image: chat
    container_name: chat
    build: .
    environment:
      NODE_ENV: production
    ports:
      - "3000:3000"
      - "8080:8080"
    volumes:
      - ./:/usr/src/app
    links:
      - mongo
  mongo:
    container_name: mongo
    image: mongo
#   You don't need to expose this port to the outside world. Because you linked the two containers the chat app
# will be able to connect to mongodb using hostname mongodb inside the container network.
#    ports:
#      - "27017:27017"

顺便说一句,如果你跑了会发生什么:

$ docker-compose down

然后

$ docker-compose up

$ docker ps

你能看到docker ps输出中暴露的端口吗?

答案 1 :(得分:0)

您的聊天服务取决于mongo,因此您还需要在聊天中添加它

depends_on:
  - mongo

这个docker-compose文件对我有用。请注意,我正在将数据从数据库保存到本地目录。您应该将此目录添加到gitignore。

version: "3.2"
services:
  mongo:
    container_name: mongo
    image: mongo:latest
    environment:
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=password
      - NODE_ENV=production
    ports:
      - "28017:27017"
    expose:
      - 28017 # you can connect to this mongodb with studio3t
    volumes:
      - ./mongodb-data:/data/db
    restart: always
    networks:
      - docker-network
  express:
    container_name: express
    environment:
      - NODE_ENV=development
    restart: always
    build:
      context: .
      args:
        buildno: 1
    expose:
      - 3000
    ports:
      - "3000:3000"
    links:
      - mongo # link this service to the database service
    depends_on:
      - mongo
    command: "npm start" # override the default command to use nodemon in dev
    networks:
      - docker-network
networks:
  docker-network:
    driver: bridge

您还可能会发现,使用节点必须先等待mongodb容器准备就绪才能连接到数据库。