所以我处理的方式是我有两个Docker文件(
Dockerfile
和
Dockerfile.dev
)。
在
Dockerfile.dev
中,我有:
FROM node:6
RUN apt-get update
RUN apt-get install -y curl net-tools jq
ENV ROOT /usr/src/app
COPY package.json /usr/src/app/
ADD .npmrc /usr/src/app/.npmrc
WORKDIR ${ROOT}
RUN npm install
COPY . ${ROOT}
CMD [ "npm", "run", "start" ]
EXPOSE 3000
我的NPM脚本长这样
"scripts": {
....
"start": "node_modules/.bin/supervisor -e js,json --watch './src/' --no-restart-on error ./index.js",
"start-production": "node index.js",
....
},
你会注意到它使用supervisor进行启动,因此对src下的任何文件进行更改都会导致服务器重新启动,而无需重新启动docker。
最后是docker compose。
dev:
build: .
dockerfile: Dockerfile.dev
volumes:
- "./src:/usr/src/app/src"
- "./node_modules:/usr/src/node_modules"
ports:
- "3000:3000"
prod:
build: .
dockerfile: Dockerfile
ports:
- "3000:3000"
在开发模式下,它会将当前目录的
src
文件夹挂载到容器的
/usr/src/app/src
和
node_modules
目录挂载到
/usr/src/node_modules
。这样我就可以在本地进行更改并保存,卷会更新容器的文件,然后监督程序会看到此更改并重新启动服务器。
请注意,由于它不监视
node_modules
文件夹,您必须更改src目录中的另一个文件才能执行重启。