且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Docker容器中运行npm命令?

更新时间:2023-09-11 22:14:46

最终运行的图像是这样的:

The image that's finally getting run is this:

FROM nginx:alpine
COPY toborFront.conf /etc/nginx/conf.d/
EXPOSE 8080
CMD ["npm", "serve", "--port 4000"]

第一阶段没有任何效果(您可以 COPY --from = ... 个文件退出),并且如果有多个 CMD ,只有最后一个才有效果.由于您是在普通的 nginx 图片中运行此命令,因此没有 npm 命令,从而导致您看到错误.

The first stage doesn't have any effect (you could COPY --from=... files out of it), and if there are multiple CMDs, only the last one has an effect. Since you're running this in a plain nginx image, there's no npm command, leading to the error you see.

我建议在主机上使用Node进行实时开发环境.在构建并测试了应用程序并打算对其进行部署后,请在适当的情况下使用Docker.在您的Dockerfile中,在第一阶段运行 ng build 将应用程序编译为静态文件,在第二阶段添加 COPY --from = ... 以获取将应用程序内置到Nginx图像中,并删除所有 CMD 行( nginx 具有适当的默认 CMD ).@VikramJakhar的 answer 有一个更完整的Dockerfile显示了这一点.

I'd recommend using Node on the host for a live development environment. When you've built and tested your application and are looking to deploy it, then use Docker if that's appropriate. In your Dockerfile, run ng build in the first stage to compile the application to static files, add a COPY --from=... in the second stage to get the built application into the Nginx image, and delete all the CMD lines (nginx has an appropriate default CMD). @VikramJakhar's answer has a more complete Dockerfile showing this.

看起来您可能正在尝试在Docker中同时运行Nginx和Angular开发服务器.如果这是您的目标,则需要在两个单独的容器中运行它们.为此:

It looks like you might be trying to run both Nginx and the Angular development server in Docker. If that's your goal, you need to run these in two separate containers. To do this:

  • 将此Dockerfile拆分为两个.将 CMD ["npm","serve"] 行放在第一个(仅角度)Dockerfile的末尾.
  • docker-compose.yml 文件中添加第二个块以运行第二个容器.后端 npm serve 容器不需要发布 ports:.
  • 将Nginx配置中的后端服务器的主机名从 localhost 更改为另一个容器的Docker Compose名称.
  • Split this Dockerfile into two. Put the CMD ["npm", "serve"] line at the end of the first (Angular-only) Dockerfile.
  • Add a second block in the docker-compose.yml file to run the second container. The backend npm serve container doesn't need to publish ports:.
  • Change the host name of the backend server in the Nginx config from localhost to the Docker Compose name of the other container.