dockernpmdocker-composedocker-volumedocker-build

Why docker-compose volume binding didn't work during the build? Should I always COPY necessary for build files?


I use docker compose with very basic node image configuration. I can use npm install after the container build. But I want to do so during it and the volumes I've bound in docker-compose.yaml seems not to work then, only after the build.

Is it right behavior? If yes then should I just COPY package.json file during build to install it? The thing that bothers me here, is that I need to make the context for a build a lot wider, to get the file from the different folder (../frontend/package.json), which seems wrong, but is it a big deal?

The error Could not read package.json: Error: ENOENT: no such file or directory, open '/var/www/html/frontend/package.json'

docker-compose.yaml

  node:
    container_name: ${PROJECT_NAME}_node
    build:
      context: ./node
    command:
      - npm run dev -- --host
    ports:
      - '8012:5173'
    volumes:
      - ./frontend:/var/www/html/frontend

DockerFile

FROM node:latest

WORKDIR /var/www/html/frontend

RUN npm install
RUN npm run build

Solution

  • With Dockerfile you can build Docker images, and the Docker Compose creates containers from existing images. Or you can combine the two commands in the compose file (with the build option) and round the docker compose up -d --build command. This command first builds the image - same when you run the docker build --tag image_name . command. Finally, create the containers.

    So if you want to run npm install on build time you need to add the required files to the image with COPY or ADD command in the Dockerfile