我试图在开发模式下在Docker容器中运行一个 Angular 应用程序,但是当我使用docker-compose build运行它时,它可以正常工作,但是当我尝试放置容器时,出现以下错误:
ERROR: for sypgod Cannot start service sypgod: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"npm\": executable file not found in $PATH
真正的问题是它无法识别npm命令,但是为什么呢?
设置如下:
Docker容器(Nginx反向代理-> Angular在端口4000中运行)
我知道有更好的部署方法,但是由于某些个人原因,目前我需要此设置
Dockerfile:
FROM node:10.9
COPY package.json package-lock.json ./
RUN npm ci && mkdir /angular && mv ./node_modules ./angular
WORKDIR /angular
RUN npm install -g @angular/cli
COPY . .
FROM nginx:alpine
COPY toborFront.conf /etc/nginx/conf.d/
EXPOSE 8080
CMD ["nginx", "-g", "daemon off;"]
CMD ["npm", "serve", "--port 4000"]
NginxServerSite
server{
listen 80;
server_name sypgod;
location / {
proxy_read_timeout 5m;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://localhost:4000/;
}
}
Docker Compose文件(我遇到问题的重要部分)
sypgod: # The name of the service
container_name: sypgod # Container name
build:
context: ../angular
dockerfile: Dockerfile # Location of our Dockerfile
最佳答案
最终运行的图像是这样的:
FROM nginx:alpine
COPY toborFront.conf /etc/nginx/conf.d/
EXPOSE 8080
CMD ["npm", "serve", "--port 4000"]
第一个阶段没有任何作用(您可以从其中删除
COPY --from=...
文件),并且如果存在多个CMD
,则只有最后一个有作用。由于您是在纯nginx
图像中运行此命令的,因此没有npm
命令,从而导致您看到错误。我建议在主机上使用Node进行实时开发环境。在构建并测试了应用程序并打算对其进行部署后,请在适当的情况下使用Docker。在Dockerfile中,在第一阶段运行
ng build
将应用程序编译为静态文件,在第二阶段中添加COPY --from=...
将已构建的应用程序添加到Nginx镜像中,然后删除所有CMD
行(nginx
具有适当的默认CMD
)。 @VikramJakhar的answer显示了一个更完整的Dockerfile。看来您可能正在尝试在Docker中同时运行Nginx和Angular开发服务器。如果这是您的目标,则需要在两个单独的容器中运行它们。去做这个:
CMD ["npm", "serve"]
行放在第一个(仅 Angular )Dockerfile的末尾。 docker-compose.yml
文件中添加第二个块以运行第二个容器。后端npm serve
容器不需要发布ports:
。 localhost
更改为另一个容器的Docker Compose名称。 关于node.js - 如何在Docker容器中运行npm命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60074174/