如何将我的本地源文件安装到docker容器?

我是新来的docker,我已经创build了我的自定义图像。

这是我的Dockerfile

FROM node:latest MAINTAINER FF COPY . /var/www WORKDIR /var/www RUN npm install EXPOSE 3000 ENTRYPOINT ["npm", "start"] 

然后我build立一个图像

 docker build -t test/node . 

形象build成后,我跑了

 docker run -p 8888:3000 -v $(pwd):/var/www -w "/var/www" test/node 

我使用-v,因为我想挂载我的主机src文件夹到/var/www

它回来了

 > expresssite@0.0.0 start /var/www > node ./bin/www module.js:472 throw err; ^ Error: Cannot find module 'express' at Function.Module._resolveFilename (module.js:470:15) at Function.Module._load (module.js:418:25) at Module.require (module.js:498:17) at require (internal/module.js:20:19) at Object.<anonymous> (/var/www/app.js:1:77) at Module._compile (module.js:571:32) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:488:32) at tryModuleLoad (module.js:447:12) at Function.Module._load (module.js:439:3) npm info lifecycle expresssite@0.0.0~start: Failed to exec start script npm ERR! Linux 4.4.39-moby npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start" npm ERR! node v7.4.0 npm ERR! npm v4.0.5 npm ERR! code ELIFECYCLE npm ERR! expresssite@0.0.0 start: `node ./bin/www` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the expresssite@0.0.0 start script 'node ./bin/www'. npm ERR! Make sure you have the latest version of node.js and npm installed. npm ERR! If you do, this is most likely a problem with the expresssite package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! node ./bin/www npm ERR! You can get information on how to open an issue for this project with: npm ERR! npm bugs expresssite npm ERR! Or if that isn't available, you can get their info via: npm ERR! npm owner ls expresssite npm ERR! There is likely additional logging output above. npm WARN Local package.json exists, but node_modules missing, did you mean to install? npm ERR! Please include the following file with any support request: npm ERR! /var/www/npm-debug.log 

我认为问题是我的src文件夹没有快速模块,但我已经在我的图像中做了npm安装,我认为这就是我所需要的。

我做错了什么? 任何人都可以帮助我吗? 非常感谢!

问题是COPY和音量的结合

发生了什么

  1. 您在创build映像时将源代码复制到Docker映像
  2. npm install在映像中运行(因此不会影响源代码)
  3. 但是,当你安装卷时,它会覆盖/ var / www,从而有效地执行步骤1和2

你想要做的是在启动docker之前或者在里面运行npm install。

您在映像中的/ var / www文件夹中运行npm安装的位置创build了一个映像。 这个安装没有发生在你的主机文件系统上。

然后,您使用该映像启动一个容器并将主机文件系统挂载到/ var / www。 覆盖图像中该位置处的所有内容,因此,在该位置执行的事先安装除非在主机上运行,​​否则不可见。

您的select包括:

  • 更加有select性的关于你装入你的容器的文件/文件夹,也许你所有的代码进入一个子目录,然后你就可以装载它。
  • 在您的主机上执行npm安装。 您可以将其作为容器启动的一部分执行,以便可执行文件位于容器内部(如果需要)。
  • 为每次更改重build容器。 不是很理想,但可以重新构造Dockerfile命令,以便只在最后复制最常见的更改,以便docker可以caching以前的图层。