一步步教你利用Docker设置Node.js(2)

version: "3" services: app: container_name: app # How the container will appear when listing containers from the CLI image: node:10 # The <container-name>:<tag-version> of the container, in this case the tag version aligns with the version of node user: node # The user to run as in the container working_dir: "/app" # Where to container will assume it should run commands and where you will start out if you go inside the container networks: - app # Networking can get complex, but for all intents and purposes just know that containers on the same network can speak to each other ports: - "3000:3000" # <host-port>:<container-port> to listen to, so anything running on port 3000 of the container will map to port 3000 on our localhost volumes: - ./:/app # <host-directory>:<container-directory> this says map the current directory from your system to the /app directory in the docker container command: "npx pm2 start ecosystem.config.js --no-daemon" # The command docker will execute when starting the container, this command is not allowed to exit, if it does your container will stop networks: app:

更改docker-compose.yml文件不会影响已经运行的容器。为了进行更改,您应该重新启动容器:

docker-compose restart

4.使我们的应用程序易于开发

您可能已经注意到,一旦Node进程启动,那么在重新启动Node进程之前,更改代码实际上并没有做任何事情,对于我们而言,每次都会涉及重新启动Docker容器以激活我们做出的改变。如果我们在进行代码更改时自动为我们重新启动Node进程,那将是理想的选择。

在过去,我已经完成了诸如引入文件监视实用程序和使用该文件监视实用程序来重新启动Docker进行文件更改之类的操作,或者我会使用Nodemon但是在使用Docker时会有一些警告。

最近,当文件发生变化时,我一直在使用PM2来重新启动我的Node进程,而且由于我们已经从上一步中获取了它,因此我们不必安装另一个依赖项。

ecosystem.config.js(仅添加了watch选项):

const path = require('path')

module.exports = { apps: [{ name: 'app', script: 'src/index.js', instances: 1, autorestart: true, watch: process.env.NODE_ENV !== 'production' ? path.resolve(__dirname, 'src') : false, max_memory_restart: '1G' }] }

如果我们没有将NODE_ENV环境变量设置为production,则上面的配置文件现在将监视src目录。您可以通过更改index.js文件来测试它,除了Hello World之外还可以将其他内容打印到浏览器中!。在此之前,您需要重新启动Docker容器,因为您更改了PM2运行容器的方式:

docker-compose restart

重新启动Node进程可能需要一秒钟才能完成,如果你想观察它何时完成,你可以看到你的Docker日志告诉PM2何时完成重启你的Node Process:

docker-compose logs -f

总结

我们的目标之一是能够轻松更改Node版本,您可以通过更改docker-compose.yml文件中的image选项来完成此操作。

本地安装依赖项是使用本地NPM和Node版本完成的,如果您的本地版本与Dockers不同,有时可能会导致冲突。使用相同的Docker容器来安装依赖项更安全。您可以使用此命令来使用该容器来安装依赖项,然后将其删除

docker run --rm -i -v <absolute-path-to-your-project-locally>:/app -w /app node:10 npm install

如上所述,具有与Docker运行的Node不同的本地版本可能是有问题的。最好在容器内部运行命令以保持一致性。你可以进入一个容器

docker exec -it app bash

上面的命令将把你放到容器中,这样你就可以继续从里面运行命令,即npm run start或npm run test

如果您不想进入容器内部,可以运行这样的命令

docker exec -t app bash -c "npm run start"

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/8e8f6e33d9b134baea5f098f35edcbc0.html