繁体   English   中英

如何将本地源文件挂载到Docker容器?

[英]How to mount my local source file to docker container?

我是Docker的新手,并且创建了自定义映像。

这是我的Dockerfile

FROM node:latest

MAINTAINER FF

COPY . /var/www

WORKDIR /var/www

RUN npm install  

EXPOSE 3000

ENTRYPOINT ["npm", "start"]

然后,我用

docker build -t test/node .

生成图像后,我跑了

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文件夹没有Express模块​​,但是我已经在映像中安装了npm,我认为这就是我所需要的。

我做错了什么? 有人可以帮我吗? 非常感谢!

问题是COPY和音量的结合

发生了什么

  1. 您在创建映像时将源代码复制到Docker映像
  2. npm install在映像内运行(因此不影响您的源代码)
  3. 但是,当您挂载该卷时,它会覆盖/ var / www,从而有效地使步骤1和2无用。

您想要做的是在启动docker之前或在docker内部运行npm install。

您在映像内的/ var / www文件夹中运行npm安装的位置创建了映像。 此安装未在主机文件系统上进行。

然后,您使用该映像启动了一个容器,并将主机文件系统安装到/ var / www。 这会覆盖映像中该位置上存在的所有内容,因此除非您在主机上运行它们,否则看不到您在该位置上完成的先前安装。

您的选择包括:

  • 对于将哪些文件/文件夹装入容器,要有更多选择,也许所有代码都放在一个子目录中,然后再装入。
  • 在主机上执行npm安装。 您可以在容器启动过程中执行此操作,以使可执行文件位于容器内部(如果需要)。
  • 为您进行的每个更改重建容器。 这并不理想,但是您可以重组Dockerfile命令,以便仅在最后复制最频繁的更改,以便Docker可以缓存先前的层。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM