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
2
Answers
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 thedocker 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 DockerfileYou cannot mount volumes this way during build.
If you use buildkit, there are ways to mount volumes during build, but it’s done differently, and probably for a different reason.
As far as I know, there are only limited options for this when using compose. For example ssh.
In your case, however, an alternative solution could be a
COPY
instruction.This probably requires restructuring of your project. As the frontend dir is a sibling of your context, and copying from there is not allowed.