I have a nestJS application using Dockerfile to build
backend/Dockerfile
FROM node:18-alpine
# Reuse the old commits if dependencies are not changed
ADD package.json /tmp/package.json
RUN cd /tmp && npm install
RUN mkdir -p /app && cp -a /tmp/node_modules /app
WORKDIR /app
COPY . .
RUN npm run build // dist file is supposed to be generated in this step
CMD [ "npm", "run", "dev" ]
I use Docker Compose for bootstrap my entire applications
docker-compose.yml
version: '3.5'
services:
backend:
build:
context: ./backend
dockerfile: Dockerfile
container_name: backend
ports:
- '3001:3001'
volumes:
- ./backend:/app
depends_on:
- database
database:
image: mongo:6.0
container_name: mongodb
restart: always
ports:
- '27017:27017'
environment:
MONGO_INITDB_ROOT_USERNAME: 'XXX'
MONGO_INITDB_ROOT_PASSWORD: '1234'
However when I run docker-compose up -d
, the dist file is not generated in the docker container. Below is the result of docker logs -f backend
> nest start --watch -b swc
> SWC Running...
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Failed to compile 20 files with swc.
Watching for file changes.
Error: Cannot find module '/app/dist/main'
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:1134:15)
at Function.Module._load (node:internal/modules/cjs/loader:975:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:128:12)
at node:internal/main/run_main_module:28:49
I tried to run npm run build
locally to manually build a dist
file to sync to the container, but whenever I run docker-compose up -d
it just disappeared.
How to fix it?
Update 1
I tried to run docker exec -it backend sh
, and run npm run build
, a dist
is created. However when I run npm run dev
, the dist
file disappeared and the exact error shown
package.json
"scripts": {
"build": "nest build",
"dev": "nest start --watch -b swc",
...
},
2
Answers
I finally solved it by
docker exec -it backend sh
npm install
No idea why it solves the issue
Use
node dist/main
instead ofnest start ...
.nest start
compiles and runs an application, this should not be used in Docker container.