0
0

More than 3 years have passed since last update.

docker nodejs を利用時にnode_modulesが作成されなくなった

Posted at

Description

gatsbyやangularでdockerを利用する際に、OSによりinstall内容が変わるmoduleがあり、手元のnode_modulesをそのままdocker環境で利用した場合にErrorを吐く場合があった。
dockerとlocalの環境で別にinstallしようと思い、docker-ignoreに追加 + docker内部でインストールを実施した際にエラーがでたため対処方法を追記。

Refs

関係ありそうだけどさっとしか見なかった。ごめんなさい。

TL;DR

volumesにnode_modulesに追記する。

docker-compose.yml
services:
  app:
    volumes: 
      - type: volume
        source: dependencies
        target: /${WORK_DIRECTORY}/node_modules
    command: yarn dev
volumes:
  dependencies:

対処方法

node_modulesをvolumeデータとして扱う

databaseのデータと同じく、volumeにnode_moduluesを追加する。
雑に使ったdockerfile

docker/server.dockerfile
FROM node:16-alpine3.11

WORKDIR /app

COPY package*.json ./
COPY yarn.lock ./

RUN rm -rf node_modules
RUN yarn install --frozen-lockfile

簡易的に作ったdocker-compose.yml

docker-compose.yml
version: "3.9"

services:
  app:
    container_name: app
    build:
      context: .
      dockerfile: ./docker/server.dockerfile
    tty: true
    restart: always
    ports:
      - "3000:3000"
    volumes: 
      - type: bind
        source: .
        target: /app
      - type: volume  # volumeをtypeで指定
        source: dependencies  # volumeに記載した名前と同じもの
        target: /app/node_modules # 利用しようとしている場所をtargetに記載
    command: yarn dev
volumes:
  db-data:
  dependencies: # volumeに登録する

気付いた点

  • dockerfileをXXX.dockerfileにするとVSCのファイルにiconがつく
  • volumeで利用したため、複数のcontainerで使い回せる
  • nocopyを使うとcontainerで相互更新しなくても利用できる
  • cli系統のpackageを別のcontainerで区分けでき、 app: &node_containerで使い回しができる
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0