Install node_modules inside Docker container and synchronize them with host

前端 未结 10 1400
旧巷少年郎
旧巷少年郎 2020-12-12 11:33

I have the problem with installing node_modules inside the Docker container and synchronize them with the host. My Docker\'s version is 18.03.1-ce, build

10条回答
  •  渐次进展
    2020-12-12 12:09

    I'm not sure to understand why you want your source code to live inside the container and host and bind mount each others during development. Usually, you want your source code to live inside the container for deployments, not development since the code is available on your host and bind mounted.

    Your docker-compose.yml

    frontend:
      volumes:
        - ./app/frontend:/usr/src/app
    

    Your Dockerfile

    FROM node:10
    
    RUN mkdir -p /usr/src/app
    WORKDIR /usr/src/app
    

    Of course you must run npm install first time and everytime package.json changes, but you run it inside the container so there is no cross-platform issue: docker-compose exec frontend npm install

    Finally start your server docker-compose exec frontend npm start

    And then later, usually in a CI pipeline targetting a deployment, you build your final image with the whole source code copied and node_modules reinstalled, but of course at this point you don't need anymore the bind mount and "synchronization", so your setup could look like :

    docker-compose.yml

    frontend:
      build:
        context: ./app/frontend
        target: dev
      volumes:
        - ./app/frontend:/usr/src/app
    

    Dockerfile

    FROM node:10 as dev
    
    RUN mkdir -p /usr/src/app
    WORKDIR /usr/src/app
    
    FROM dev as build
    
    COPY package.json package-lock.json ./
    RUN npm install
    
    COPY . ./
    
    CMD ["npm", "start"]
    

    And you target the build stage of your Dockerfile later, either manually or during a pipeline, to build your deployment-ready image.

    I know it's not the exact answer to your questions since you have to run npm install and nothing lives inside the container during development, but it solves your node_modules issue, and I feel like your questions are mixing development and deployment considerations, so maybe you thought about this problem in the wrong way.

提交回复
热议问题